iOS XCode send and read email example
Send and receive email in Swift using MailSlurp email API
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
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)"
}
}