Here is an example of how to send and read email using iOS XCode.

How to Use MailSlurp Email API with Xcode to Send and Receive Emails in Swift: A Comprehensive Guide for iOS App Developers

  • Table of contents

How to send and receive email in Swift using MailSlurp email API in conjunction with Xcode. For a more generalized guide see the send emails in Swift example.

About

MailSlurp is a library with iOS/iPadOS/MacOS/TVOS support via swift and objective C for sending an receiving emails from real email addresses in code an tests. Use MailSlurp to test iOS apps end-to-end using test email accounts or embed MailSlurp to send and receive emails from apps.

Install MailSlurp in XCode

To get started using MailSlurp first create a new XCode project

1

3 4 5 7 8 9 10 6

Alternative Package.swift installation

You can also use Package.swift and Swift Package Manager to install MailSlurp:

// 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"]),
    ]
)

Run swift package resolve to install dependencies.

Using MailSlurp in Swift code

The MailSlurp library creates controllers for every endpoint on the MailSlurp REST API

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)"
    }
  }