How to Receive Email in Swift: Read the Inbox, Save Attachments and Handle Vapor Webhooks

Receive email in Swift and read it without IMAP: create an address, wait for a message, save attachments, and handle new mail in a Vapor webhook.

By · · 12 min read

Swift code that reads the newest message in a Mailcycle inbox with the Swift SDK

You want to receive email in Swift: read a supplier’s invoice and save the PDF, pick a sign-in code out of a verification email in a test, or hand a customer’s reply to your Vapor service. Foundation can build a mail composer or call an SMTP library to send, and has no client for reading mail, so receiving usually means an IMAP package, a mailbox and its password, or an SMTP server of your own plus a MIME parser. If what you want is “give my program an address and let it read what arrives”, an email API is shorter.

This tutorial shows how to receive and read email in Swift with the Mailcycle Swift SDK. You’ll create an address, list and open messages, save attachments to disk, wait for the next email, and then get new mail pushed to a Vapor route by webhook.

It is the receiving half of How to send email from Swift, which covers sending, HTML, attachments you send and threaded replies. This one goes deep on the inbox.

Quick answer: how to receive email in Swift

Add the package, sign in with your recovery phrase, create an address, and call waitFor. It returns when a message arrives, parsed and decrypted, with the sender, subject, text, HTML and attachments as plain properties.

import Foundation
import Mailcycle

let env = ProcessInfo.processInfo.environment
let mc = try await Mailcycle.signIn(phrase: env["MAILCYCLE_PHRASE"]!)

let address = try await mc.addresses.create(NewAddress(prefix: "inbound", label: "Swift inbox"))
print("Send an email to", address.emailAddress)

let message = try await mc.messages.waitFor(WaitFor(addressId: address.id, timeout: 300))
print(message.fromAddress, message.subject)
print(message.text)

Run it, send an email to the address it prints from any mail app, and the program prints what you sent. The rest of this guide is what a real service needs around that: paging, attachments, push and errors.

Flow: a sender writes to your address, Mailcycle encrypts the mail on arrival, the Swift SDK lists, waits for or receives it by webhook, and your Swift code reads the message
Mail sent to a Mailcycle address is encrypted on arrival, then your Swift code reads it with the Swift SDK, by waiting for it or from a webhook.

Prerequisites

  • Swift 5.9 or later. The package runs on macOS 13, iOS 16 and Linux. Check with swift --version, or get a toolchain from swift.org.
  • A Mailcycle account. Receiving works on every plan when your program signs in with the recovery phrase. API keys and webhooks start at Operator. Pricing has the plans.
  • Your recovery phrase, in an environment variable named MAILCYCLE_PHRASE, for any process that opens mail.
  • For the webhook example: an existing Vapor 4 project. The Mailcycle parts work just as well in Hummingbird or a plain executable.

Step 1: Add the Mailcycle package

The package is served over Git from mailcycle.email. Swift Package Manager takes any Git URL, so it resolves like any other dependency, with versions taken from its tags. Add it to Package.swift:

// swift-tools-version:5.9
import PackageDescription

let package = Package(
    name: "Inbox",
    platforms: [.macOS(.v13)],
    dependencies: [
        .package(url: "https://mailcycle.email/swift/mailcycle.git", from: "0.3.0"),
    ],
    targets: [
        .executableTarget(
            name: "Inbox",
            dependencies: [.product(name: "Mailcycle", package: "mailcycle")]
        ),
    ]
)

The API is async throughout, with value types you can pass between tasks. It has handles on the client: mc.addresses, mc.messages, mc.webhooks and mc.events.

Step 2: Sign in and create an address

Mailcycle.signIn(phrase:) works on every plan. Each sign-in opens a 30-day session, so a program that runs often can keep mc.sessionToken and pick it up again with Mailcycle.resume(sessionToken:phrase:).

An address that receives mail needs a public key the mail server can encrypt to. addresses.create derives that key from your phrase and uploads only the public half.

let address = try await mc.addresses.create(NewAddress(
    prefix: "invoices",
    label: "Supplier invoices",
    retentionDays: 30
))
print(address.emailAddress, address.id)

for existing in try await mc.addresses.list() {
    print(existing.emailAddress, existing.label ?? "", existing.receives)
}

The fields on NewAddress:

  • prefix: "invoices" gives invoices- plus a random ending on a shared domain.
  • style (.person, .business, .team or .neutral) rolls a name in that style.
  • localPart asks for an exact name. Any name you type needs Scale or above, and so does domain with your own domain.
  • label is encrypted on your machine, so the server stores it as ciphertext.
  • retentionDays is 1 to 90, and 7 when left out.

Save address.id, the ibx_... id: every reading call takes it.

Step 3: List and read emails in the inbox

messages.list returns one page of a folder, newest first:

let page = try await mc.messages.list(address.id, limit: 20)
for message in page.messages {
    let flag = message.read ? " " : "*"
    print(flag, message.receivedAt, message.fromAddress, message.subject)
}

if let cursor = page.nextCursor {
    let older = try await mc.messages.list(address.id, limit: 20, cursor: cursor)
    print(older.messages.count, "older messages on the next page")
}

nextCursor is opaque: pass it back as cursor as it came, and it is nil on the last page. To walk a whole folder, all pages for you:

let all = try await mc.messages.all(address.id)

let invoices = all.filter { message in
    message.subject.lowercased().contains("invoice") && !message.attachments.isEmpty
}
print(invoices.count, "invoices with files attached")

Message content is encrypted, so you decrypt and then filter in Swift, as above. Pass folder: "sent", "junk", "trash" or "starred" to read another one.

What is in a Message

Each Message is a plain struct, already parsed from MIME and decrypted:

Property What it holds
id, addressId The message’s msg_... id and the address it arrived at.
receivedAt When it arrived, as an RFC 3339 string in UTC.
fromAddress, fromName The sender’s address and display name.
replyTo Where a reply should go: the Reply-To header if set, otherwise From.
to, subject The recipient and the subject line.
text The plain-text body.
html The HTML body exactly as sent. Do not render this one.
safeHTML The HTML with remote images, trackers and embeds removed.
attachments An array of Attachment: index, filename, mimeType, size, contentId, stored.
messageId The sender’s Message-ID header, used to thread a reply.
read, starred, folder The message’s state.
opened false if it could not be decrypted: no phrase, or the wrong one.

A message that does not open comes back with opened set to false and empty content rather than an error, so one bad message never hides the rest of a page.

Read the email body in Swift: text, html and safeHTML

Most mail carries a plain-text and an HTML part. Use text for anything you parse, such as codes, order numbers or a reply to hand to a model. If you show the HTML anywhere, use safeHTML:

let message = try await mc.messages.get("msg_91be02c4a7d1")
guard message.opened else {
    fatalError("this message did not open: check the recovery phrase")
}

print(message.text.isEmpty ? "(no plain-text part)" : message.text)

if !message.safeHTML.isEmpty {
    try message.safeHTML.write(toFile: "preview.html", atomically: true, encoding: .utf8)
    print(message.blocked.count, "remote items taken out")
}

get fetches one message by id, from any folder. safeHTML is the HTML the Mailcycle apps show: remote images, tracking pixels and embeds are taken out, so opening it does not tell the sender when you read it. In a WKWebView or a SwiftUI web view, load safeHTML and never html.

Download email attachments in Swift

Attachments are listed on the message and fetched one at a time. Their bodies are encrypted like the message, and attachment(_:index:) opens them on your machine. This function saves a message’s files safely:

func saveAttachments(_ mc: Mailcycle, _ message: Message, into folder: URL) async throws -> [URL] {
    let target = folder.appendingPathComponent(message.id, isDirectory: true)
    var saved: [URL] = []
    for attachment in message.attachments {
        guard attachment.stored else { continue }          // an empty part: nothing to fetch
        guard attachment.contentId == nil else { continue } // an image the HTML shows inline, like a logo

        let data = try await mc.messages.attachment(message, index: attachment.index) // opened on this machine
        try FileManager.default.createDirectory(at: target, withIntermediateDirectories: true)

        var name = URL(fileURLWithPath: attachment.filename.replacingOccurrences(of: "\\", with: "/")).lastPathComponent
        if name.isEmpty || name == "/" || name == "." || name == ".." {
            name = "attachment"
        }
        let url = target.appendingPathComponent("\(attachment.index)-\(name)")
        try data.write(to: url, options: .atomic)
        saved.append(url)
    }
    return saved
}

Then process every unread message that has files, and mark each one read so the next run skips it:

let downloads = URL(fileURLWithPath: "downloads", isDirectory: true)

for message in try await mc.messages.all(address.id) where !message.read && !message.attachments.isEmpty {
    for url in try await saveAttachments(mc, message, into: downloads) {
        print("saved", url.path)
    }
    try await mc.messages.markRead(message.id)
}

The details that matter with real mail:

  • The file name comes from the sender. A name like ../../.bashrc is a classic path-traversal trick. lastPathComponent keeps the last path component, and the index prefix keeps two files called invoice.pdf apart.
  • stored is false for a part that had no body. Skip it.
  • contentId marks an inline image, the kind HTML shows with <img src="cid:logo">. Most pipelines want the PDF, not the logo.
  • mimeType and size let you keep only application/pdf, or refuse anything over a size, before you download it.
  • Treat files as untrusted. Scan them, or open them in a sandbox, before anything else touches them.

That is the job an email parser does for attachments, without walking a MIME tree or decoding base64.

Wait for the next email in Swift

waitFor returns when a matching message arrives, opened. It is the shortest way to read a verification email in an end-to-end test, or to wait for a reply:

let started = Date() // take the time before the email is triggered

// ...trigger the email here: submit a sign-up form, call your own API...

do {
    let message = try await mc.messages.waitFor(WaitFor(
        addressId: address.id,
        subject: "verify",
        timeout: 120,
        since: started
    ))

    guard let range = message.text.range(of: #"\b\d{6}\b"#, options: .regularExpression) else {
        fatalError("no code in: \(message.text)")
    }
    print("code:", message.text[range])
} catch let error as MailcycleError where error.code == "timeout" {
    print("no verification email within two minutes")
}

How it behaves:

  • since is the important one. Mail received from that moment on counts, even if it landed before the wait began. Take the time before you trigger the email, so a fast delivery cannot slip past. It defaults to when waitFor is called.
  • from and subject match text the sender or subject contains, ignoring case. addressId limits the wait to one address.
  • timeout is in seconds, 60 by default. When it runs out you get a MailcycleError.api with the code timeout.
  • pollEvery (five seconds by default) is how often it checks when the live stream is not available.

In an XCTest, create the address at the top and delete it when the test ends:

import Mailcycle
import XCTest

final class VerificationEmailTests: XCTestCase {
    func testSignUpSendsACode() async throws {
        let phrase = try XCTUnwrap(ProcessInfo.processInfo.environment["MAILCYCLE_PHRASE"])
        let mc = try await Mailcycle.signIn(phrase: phrase)

        let address = try await mc.addresses.create(NewAddress(prefix: "test", retentionDays: 1))
        addTeardownBlock { try await mc.addresses.delete(address.id) }

        let started = Date()
        // ...sign up with address.emailAddress in the app under test...

        let message = try await mc.messages.waitFor(WaitFor(addressId: address.id, timeout: 120, since: started))
        XCTAssertTrue(message.subject.lowercased().contains("verify"))
    }
}

Mark as read, star, move and delete

These calls change state only, so they do not open any content:

Call What it does
mc.messages.markRead(id) Marks read. markRead(id, read: false) marks unread.
mc.messages.star(id) Stars it. star(id, starred: false) unstars.
mc.messages.move(id, to: "junk") Moves to "inbox", "junk" or "trash".
mc.messages.restore(id) Puts it back where it was before junk or trash.
mc.messages.delete(id) Deletes it now.

Get new email pushed to Vapor with a webhook

Mailcycle can tell your service the moment mail arrives. A message.received event carries the message’s id and its address’s id. Your code fetches the message by id and opens it locally, so the phrase stays on your machine.

Add a webhook in the app under API, on the Webhooks tab, or from Swift with a signed-in session:

let created = try await mc.webhooks.create(
    url: "https://example.com/hooks/mailcycle",
    events: ["message.received"],
    name: "Inbound mail"
)
print(created.webhook.id, created.secret) // whsec_..., shown once: store it as MAILCYCLE_WEBHOOK_SECRET

The URL must be HTTPS. For local development, expose your dev server through a tunnel. Then the receiving route. Create the client once in configure(_:) and keep it in Application.storage:

import Mailcycle
import Vapor

struct MailcycleKey: StorageKey {
    typealias Value = Mailcycle
}

struct WebhookSecretKey: StorageKey {
    typealias Value = String
}

extension Application {
    var mailcycle: Mailcycle {
        get { storage[MailcycleKey.self]! }
        set { storage[MailcycleKey.self] = newValue }
    }

    var webhookSecret: String {
        get { storage[WebhookSecretKey.self]! }
        set { storage[WebhookSecretKey.self] = newValue }
    }
}

// configure.swift
public func configure(_ app: Application) async throws {
    guard let phrase = Environment.get("MAILCYCLE_PHRASE"),
        let secret = Environment.get("MAILCYCLE_WEBHOOK_SECRET")
    else {
        fatalError("Set MAILCYCLE_PHRASE and MAILCYCLE_WEBHOOK_SECRET")
    }
    app.mailcycle = try await Mailcycle.signIn(phrase: phrase)
    app.webhookSecret = secret
    try routes(app)
}

The route checks the signature, answers straight away, and does the fetching in a task:

import Mailcycle
import Vapor

actor SeenEvents {
    private var ids = Set<String>() // one process only: use a table with a unique key in production

    func isNew(_ id: String) -> Bool {
        ids.insert(id).inserted
    }
}

func routes(_ app: Application) throws {
    let seen = SeenEvents()

    app.on(.POST, "hooks", "mailcycle", body: .collect(maxSize: "1mb")) { req async throws -> HTTPStatus in
        // The exact body, before any parsing.
        let raw = req.body.data.map { [UInt8]($0.readableBytesView) } ?? []
        let signature = req.headers.first(name: "Mailcycle-Signature")
        guard verifyWebhookSignature(secret: req.application.webhookSecret, rawBody: raw, header: signature) else {
            return .unauthorized
        }
        if let id = req.headers.first(name: "Mailcycle-Event-Id"), await !seen.isNew(id) {
            return .noContent // a retry of an event already handled
        }

        let event = try JSONValue.parse(raw)
        if event["type"].string == "message.received", let messageId = event["payload"]["messageId"].string {
            let mc = req.application.mailcycle
            let logger = req.logger
            Task { await process(mc, messageId, logger) } // answer fast, then do the work
        }
        return .noContent
    }
}

func process(_ mc: Mailcycle, _ messageId: String, _ logger: Logger) async {
    do {
        let message = try await mc.messages.get(messageId) // fetched by id, opened here
        guard message.opened else { return }
        let saved = try await saveAttachments(mc, message, into: URL(fileURLWithPath: "downloads"))
        logger.info("\(message.fromAddress): \(message.subject) (\(saved.count) files)")
        try await mc.messages.markRead(message.id)
    } catch {
        logger.error("could not process \(messageId): \(error)")
    }
}

saveAttachments is the function from the attachments section. What each part is for:

  • The signature is an HMAC-SHA256 of the timestamp and the raw body, keyed with your whsec_ secret. verifyWebhookSignature checks it in constant time and refuses a timestamp more than five minutes old. Check the bytes as they arrived: a body that was decoded and re-encoded will not match.
  • Answer fast. Mailcycle waits 10 seconds for a 2xx. The route replies first and does the fetching and saving in a Task.
  • Deduplicate. An event can arrive more than once, and Mailcycle-Event-Id is the same on every attempt. The actor suits one process. With several instances, insert the id into a table with a unique constraint.
  • Hummingbird follows the same steps: read the raw body, verify, fetch by id.

You can test the route without a live webhook. WebhookSignature.header(secret:rawBody:timestamp:) builds the header Mailcycle would send. Retries, the delivery log and every event type are in the webhooks guide, and Receive email with a webhook walks through the receiver in more depth.

For a command-line tool or a macOS utility that runs only while it is open, mc.events.stream() gives the same events over a live connection. Its events property is an AsyncSequence you read with for try await event in try mc.events.stream().events.

An IMAP client and an email API in Swift

Apple’s frameworks have no IMAP client. Packages such as swift-nio-imap connect to a mailbox: you give them a host, port 993 and credentials, select the inbox, fetch messages and parse the MIME yourself.

An email API fits when your program needs addresses of its own: one per customer, per test run or per agent, created in code, with mail pushed to you as it arrives.

An IMAP package such as swift-nio-imap Mailcycle Swift SDK
Install A third-party package One .package line in Package.swift
You need An IMAP mailbox and its credentials A recovery phrase, plus an API key if you want one
New addresses Made at your mail provider mc.addresses.create() in code
Parsing Raw MIME, parsed by you Parsed properties: text, html, attachments
Tracker-free HTML Strip it yourself safeHTML, with blocked listing what was removed
Attachments Walk the MIME parts mc.messages.attachment(message, index:)
New-mail push IMAP IDLE Webhooks and mc.events.stream()
Wait for one email Write the loop yourself waitFor()
Mail at rest Depends on the provider Encrypted with keys from your recovery phrase

Wait on many addresses with a task group

Swift’s structured concurrency suits parallel waits. A TaskGroup starts one child per address and collects the results as they finish, and cancelling the parent cancels every child.

func codes(for jobs: [String]) async throws -> [String: String] {
    try await withThrowingTaskGroup(of: (String, String).self) { group in
        for job in jobs {
            group.addTask {
                let address = try await mc.addresses.create(NewAddress(prefix: job, retentionDays: 1))
                let started = Date()
                try await trigger(job, address.emailAddress)
                let message = try await mc.messages.waitFor(
                    WaitFor(addressId: address.id, timeout: 60, since: started))
                let code = message.text.range(of: #"\b\d{6}\b"#, options: .regularExpression)
                    .map { String(message.text[$0]) } ?? ""
                return (job, code)
            }
        }
        var result: [String: String] = [:]
        for try await (job, code) in group { result[job] = code }
        return result
    }
}

Share the client through an actor

The client is a reference you can share, but a small actor makes ownership explicit and gives you a place for caching the session token between launches.

enum InboxError: Error { case noCode }

actor Inbox {
    private let mc: Mailcycle
    init(phrase: String) async throws { mc = try await Mailcycle.signIn(phrase: phrase) }

    func nextCode(on address: Address) async throws -> String {
        let message = try await mc.messages.waitFor(WaitFor(addressId: address.id, subject: "verify", timeout: 60))
        guard let range = message.text.range(of: #"\b\d{6}\b"#, options: .regularExpression) else { throw InboxError.noCode }
        return String(message.text[range])
    }
}

An async XCTest

XCTest supports async test methods directly, so there is no expectation boilerplate. Create the address in setUp() and delete it in tearDown(), both marked async throws.

final class SignupEmailTests: XCTestCase {
    var mc: Mailcycle!
    var address: Address!

    override func setUp() async throws {
        mc = try await Mailcycle.signIn(phrase: ProcessInfo.processInfo.environment["MAILCYCLE_PHRASE"]!)
        address = try await mc.addresses.create(NewAddress(prefix: "xctest", retentionDays: 1))
    }
    override func tearDown() async throws { try await mc.addresses.delete(address.id) }
}

Server-side Swift with Vapor, and UI tests

On a Vapor server the client lives in the application’s storage and the webhook route reads req.body as raw bytes before verifying. For an iOS app’s UI tests, run the mail half in the test target, since the SDK works on iOS 16 and later, and drive the app with XCUIApplication. The app types the address, and the test reads the email through the SDK, never through a mail client on the simulator.

SwiftUI: show the newest message in an app

In an iOS or macOS app, load mail in a view model marked @MainActor, and keep the network calls in async functions that the view starts with .task.

@MainActor
final class InboxViewModel: ObservableObject {
    @Published var messages: [Message] = []
    private let mc: Mailcycle
    init(mc: Mailcycle) { self.mc = mc }

    func load(address: Address) async {
        messages = (try? await mc.messages.all(address.id)) ?? []
    }
}

The view calls .task { await model.load(address: address) }, which cancels the work if the view disappears. Render message.safeHTML in a web view that has JavaScript turned off, and never message.html, since the safe version has remote images, trackers and embeds removed. Because a message that cannot be opened comes back with opened set to false rather than an error, show a placeholder row for it instead of dropping it.

Linux and server builds

The package supports Linux as well as macOS 13 and iOS 16, so the same code runs in a Vapor service or a command-line tool built in a container. Add the dependency in Package.swift, build with swift build -c release, and copy the binary into a slim runtime image. Read the phrase from the environment on a server and from the Keychain in an app, and keep both out of logs.

Troubleshooting

  • A wait outlives its task. waitFor is cancelled with its task, so check for cancellation in long loops.
  • A Vapor webhook fails verification. Collect the body as bytes before decoding, because the signature is computed over the exact payload. In an app, keep the phrase in the Keychain, never in source.
  • Messages have opened set to false and empty fields. The client has no phrase, or a phrase from a different account. Build it with Mailcycle.signIn(phrase:).
  • Nothing arrives at a new address. Check address.receives in mc.addresses.list(), and check the sender used the exact address, since prefixed names have a random ending.
  • error.code is rate_limited. You are reading too much too fast. Back off, read only what is new, or switch to webhooks.
  • A 404 fetching an attachment. The part has stored set to false. Skip it.
  • The webhook route returns 401 for real deliveries. You are verifying a re-encoded body, or the wrong secret. Use the raw request bytes and the whsec_ secret of this webhook.

Every error is a MailcycleError, with error.code and error.status to match on. Every code is listed in Errors.

Reply from Swift, or hand the inbox to an agent

To answer a message in the same thread, send with to: message.replyTo and replyTo: message on an Outgoing. Sending email from Swift covers that, along with the plans that send.

If an AI agent should read the inbox, Mailcycle also runs as an MCP server with tools such as wait_for_message, read_message and read_attachment, for Claude Code, Cursor, Codex or any other MCP client. Start with Give your AI agent its own email inbox.

Next steps

FAQ

How do I receive email in Swift?

Give your program an address that receives mail, then read it with a client. With Mailcycle, add the Swift package, sign in with Mailcycle.signIn(phrase:), create an address with mc.addresses.create(NewAddress(...)), and call mc.messages.waitFor(WaitFor(...)). The message comes back parsed and decrypted: sender, subject, text, HTML and attachments.

How do I read emails from an inbox in Swift?

Call mc.messages.list(address.id, limit: 20) for one page, newest first, or mc.messages.all(address.id) to walk the whole folder. Each Message has fromAddress, subject, text, safeHTML, attachments and read.

How do I download email attachments in Swift?

Each Message lists its files in message.attachments, with filename, mimeType, size and index. Call try await mc.messages.attachment(message, index: attachment.index) to get Data, opened on your machine, and write it with data.write(to:). Clean the file name first with URL(fileURLWithPath:).lastPathComponent, because it comes from the sender.

How can a Swift program wait for a new email?

Call mc.messages.waitFor(WaitFor(addressId:subject:timeout:since:)). It returns the first matching message. If nothing matches in time it throws MailcycleError.api with the code timeout, which error.code reads for you.

How do I get notified when an email arrives in a Vapor app?

Add a webhook for message.received, point it at a Vapor route, and check each delivery with verifyWebhookSignature(secret:rawBody:header:) against the raw body. The event carries the message id, so fetch the message with mc.messages.get(). Webhooks are on the Operator plan and above.

Is there a Swift library to read email without IMAP?

Yes. The Mailcycle Swift package reads mail over HTTPS, so there is no IMAP host, port or mailbox password, and the message arrives already parsed.

Which Mailcycle plan do I need to receive email from Swift?

Every plan can create addresses, read mail and download attachments when the program signs in with the recovery phrase. API keys and webhooks start at Operator. See Plans and limits.

Why does the Swift client need my recovery phrase?

Mail is encrypted the moment it arrives, with keys from your recovery phrase. The Swift client derives the same keys on your machine and opens each message in your process. A message that does not open comes back with opened set to false.

Receive email in code