Swiftpack.co - mailslurp/mailslurp-client-swift as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
See all packages published by mailslurp.
mailslurp/mailslurp-client-swift 15.13.9
Official MailSlurp Email API Client for Swift
⭐️ 1
🕓 16 weeks ago
iOS macOS watchOS tvOS
.package(url: "https://github.com/mailslurp/mailslurp-client-swift.git", from: "15.13.9")

MailSlurp Swift Email Client

Send and receive emails in Swift and Objective C. Use the MailSlurp Swift client for managing email accounts in iOS, MacOS, TVOS, and more. Built with OpenAPI and PromiseKit.

Quick links

Install MailSlurp package

The Swift package is hosted on the Swift Package Index and GitHub. Create a new swift project using:

swift package init --type=executable

Edit Packages.swift and add https://github.com/mailslurp/mailslurp-client-swift as a package and a target dependency.

// swift-tools-version:5.5

import PackageDescription

let package = Package(
        name: "your-project",
        products: [
        dependencies: [
            .package(url: "https://github.com/mailslurp/mailslurp-client-swift", from: "15.12.5"),
        targets: [
                    name: "your-test-project",
                    dependencies: [
                        .product(name: "mailslurp", package: "mailslurp-client-swift")

MailSlurp client is built with PromiseKit (async/await for swift) so you may also want to include AwaitKit in your swift dependencies for awaiting Promise results.

Setup API Key

MailSlurp is free to use but requires an API Key. Sign up and create an API Key using the MailSlurp dashboard.

When you make requests use an API controller's withRequestBuilder method call the addHeader("x-api-key", "your-api-key") method to add authentication to your requests. For example when using the InboxController methods:

let promise = InboxControllerAPI
    .addHeader(name: "x-api-key", value: apiKey)

The full test example is as follows:

let apiKey = ProcessInfo.processInfo.environment["API_KEY"] ?? ""
    // use addHeader to add your api key to requests
    .addHeader(name: "x-api-key", value: apiKey)
    // uses PromiseKit for response handling
    .done { response in
        XCTAssertTrue(response.body?.emailAddress?.contains("@mailslurp") ?? false)
        XCTAssertTrue(response.statusCode == 201)
    }.catch { errorType in 
        // handle error, cast to mailslurp.ErrorResponse using guard to access .error(statusCode, data, _, _)

API structure

The Swift client mimics the controllers and methods of the REST API. For controller and method documentation please see the code hosted on GitHub or read the getting started guide.

Platform compatibility

MailSlurp Swift client is built to target Swift 5.x and XCode 12.x.

Platform Minimum Version
iOS v9
MacOS V10.11
WatchOS v3

Example usage

MailSlurp uses PromiseKit. To test using XCTest and MailSlurp use the example below:

import XCTest
import class Foundation.Bundle
import mailslurp

final class exampleTests: XCTestCase {
    func testExample() throws {
        let expectation = self.expectation(description: "Can create inbox")
        let apiKey = ProcessInfo.processInfo.environment["API_KEY"] ?? ""
            .addHeader(name: "x-api-key", value: apiKey)
            .done { response in
                XCTAssertTrue(response.statusCode == 201)
                XCTAssertTrue(response.body?.emailAddress?.contains("@mailslurp") ?? false)
             }.catch { errorType in
                XCTAssertFalse(true, "Should not throw exception")
        waitForExpectations(timeout: 5, handler: nil)


    /// Returns path to the built products directory.
    var productsDirectory: URL {
      #if os(macOS)
        for bundle in Bundle.allBundles where bundle.bundlePath.hasSuffix(".xctest") {
            return bundle.bundleURL.deletingLastPathComponent()
        fatalError("couldn't find the products directory")
        return Bundle.main.bundleURL

To run the test execute:

API_KEY=your-api-key swift test

Handling exceptions

Use a guard to cast errors to a mailslurp.ErrorResponse to access the status code and error message of a request.

CommonActionsControllerAPI.sendEmailSimpleWithRequestBuilder(emailOptions: sendOptions)
  .addHeader(name: "x-api-key", value: apiKey)
  .done { response in
    // handle success
  .catch(policy: .allErrors) { err in
    // handle error
    guard let e = err as? mailslurp.ErrorResponse else {
        error = err.localizedDescription
    // pattern match the error to access status code and data
    // MailSlurp returns 4xx errors when invalid parameters or
    // unsatisfiable request. See the message and status code
    switch e {
    case .error(let statusCode, let data, _, _):
        let msg = String(decoding: data!, as: UTF8.self)
        error = "\(statusCode) Bad request: \(msg)"

Awaiting promises

PromiseKit wraps MailSlurp request results in a Promise. Use .done { response in } and .catch { err in } methods to handle responses and exceptions. For easier access use AwaitKit style await functions.

let inbox = try! await(
        .addHeader(name: "x-api-key", value: apiKey)
// then access inbox.emailAddress, inbox.id etc


Stars: 1
Last commit: 16 weeks ago
jonrohan Something's broken? Yell at me @ptrpavlik. Praise and feedback (and money) is also welcome.


Release Notes

16 weeks ago

Release 15.13.9. add-scripts

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics