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

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

MailSlurp Swift Client

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

Quick links

Install MailSlurp package

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.3

import PackageDescription

let package = Package(
    name: "example",
    // add platform as mailslurp requires macOS >= v10_11
    platforms: [
        .macOS(.v10_11)
    ],
    dependencies: [
        // add mailslurp dependency
        .package(url: "https://github.com/mailslurp/mailslurp-client-swift", from: "12.4.2"),
    ],
    targets: [
        // add mailslurp to the target
        .target(
            name: "example",
            dependencies: ["mailslurp"]),
        .testTarget(
            name: "exampleTests",
            dependencies: ["mailslurp"]),
    ]
)

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 you need an API Key. Sign up and create an API Key using the MailSlurp dashboard.

Then add the GitHub release using Swift package manager for MailSlurp:

// add mailslurp dependency
.package(url: "https://github.com/mailslurp/mailslurp-client-swift", from: "12.4.2"),

When you make requests use an API controller's withRequestBuilder method and 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
    .createInboxWithDefaultsWithRequestBuilder()
    .addHeader(name: "x-api-key", value: apiKey)
    .execute()

The full test example is as follows:

let apiKey = ProcessInfo.processInfo.environment["API_KEY"] ?? ""
InboxControllerAPI.createInboxWithDefaultsWithRequestBuilder()
    // use addHeader to add your api key to requests
    .addHeader(name: "x-api-key", value: apiKey)
    .execute()
    // uses PromiseKit for response handling
    .done { response in
        XCTAssertTrue(response.body?.emailAddress?.contains("@mailslurp") ?? false)
        XCTAssertTrue(response.statusCode == 201)
        expectation.fulfill()
    }.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
TVOS v9
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"] ?? ""
        InboxControllerAPI.createInboxWithDefaultsWithRequestBuilder()
            .addHeader(name: "x-api-key", value: apiKey)
            .execute()
            .done { response in
                XCTAssertTrue(response.statusCode == 201)
                XCTAssertTrue(response.body?.emailAddress?.contains("@mailslurp") ?? false)
                expectation.fulfill()
             }.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")
      #else
        return Bundle.main.bundleURL
      #endif
    }
}

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)
  .execute()
  .done { response in
    // handle success
  }
  .catch(policy: .allErrors) { err in
    // handle error
    guard let e = err as? mailslurp.ErrorResponse else {
        error = err.localizedDescription
        return
    }
    // 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(
    InboxControllerAPI.createInboxWithDefaultsWithRequestBuilder()
        .addHeader(name: "x-api-key", value: apiKey)
        .execute()
)
// then access inbox.emailAddress, inbox.id etc

GitHub

link
Stars: 0
Last commit: 2 weeks ago

Ad: Job Offers

iOS Software Engineer @ Perry Street Software
Perry Street Software is Jack’d and SCRUFF. We are two of the world’s largest gay, bi, trans and queer social dating apps on iOS and Android. Our brands reach more than 20 million members worldwide so members can connect, meet and express themselves on a platform that prioritizes privacy and security. We invest heavily into SwiftUI and using Swift Packages to modularize the codebase.

Submit a free job ad (while I'm testing this). The analytics numbers for this website are here.

Dependencies

Release Notes

2 weeks ago

Release 15.0.2. gpa

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