How to Send Email From Swift: Vapor, iOS and Server-Side Swift
Send email from Swift with async/await: a Vapor route, HTML and attachments, threaded replies, and iOS mail without MFMailComposeViewController or SMTP.

You want to send email from Swift. Maybe it’s a Vapor backend that sends a welcome email, a receipt or a sign-in link. Maybe it’s an iOS app where tapping “Email me this report” should just work, without a compose sheet popping up. Or it’s a command-line tool on a Mac or a Linux box that mails you when a job finishes.
Swift makes this harder than it sounds. Foundation has no SMTP client. On iOS, MFMailComposeViewController opens the person’s own Mail app and waits for them to press Send, which isn’t sending from your code at all. SMTP libraries exist, but they need a mail account, its password and a server to talk to.
This tutorial covers the other route: an HTTPS email API with a native Swift package. You’ll use the Mailcycle Swift SDK to send plain-text and HTML email with async/await, add attachments, send from a Vapor route, keep API keys out of your iOS app, reply in a thread and wait for the answer, which comes back to the same inbox you sent from. Every snippet here was type-checked against the SDK’s source.
To read mail as well as send it, see How to receive email in Swift: create an address, wait for a message, save attachments and handle a Vapor webhook.
Quick answer: how do you send email from Swift?
To send email from Swift, add the Mailcycle package with Swift Package Manager, create a client on your server with Mailcycle.withAPIKey(_:), and call try await mc.messages.send(Outgoing(from:to:subject:text:)). The mail goes out from an address on your account, the call returns its Message-ID, and replies arrive back in that same inbox.
import Foundation
import Mailcycle
let env = ProcessInfo.processInfo.environment
let mc = try await Mailcycle.withAPIKey(env["MAILCYCLE_API_KEY"]!)
let result = try await mc.messages.send(Outgoing(
from: "receipts@yourdomain.com",
to: "customer@example.com",
subject: "Your receipt",
text: "Thanks for your order."
))
print(result.messageId)
That’s the whole thing. The rest of this post builds it into a real app: a server that sends, an iOS client that asks it to, and the replies coming back.
This post is part of a series on how to send email from any language. If part of your stack is in another language, there are matching guides for TypeScript, Python, Go and Rust.
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 on Scale or above. Sending with an API key needs the Scale plan. The free 7-day trial is Scale, with no card. An account is a twelve-word recovery phrase rather than an email and password, so write it down when you sign up.
- An API key. In the app, open API, then the Keys tab, and create one. The token starts with
mak_and is shown once. The quickstart walks through it. - An address to send from. Every message goes out from an address on your account. You’ll create one in Step 3 if you don’t have one yet.
- For the server examples: an existing Vapor 4 project. The Mailcycle parts work just as well in Hummingbird or a plain executable.
Step 1: Add the Mailcycle package to Package.swift
The package is served over Git from mailcycle.email rather than GitHub. 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: "Notifier",
platforms: [.macOS(.v13)],
dependencies: [
.package(url: "https://mailcycle.email/swift/mailcycle.git", from: "0.3.0"),
],
targets: [
.executableTarget(
name: "Notifier",
dependencies: [.product(name: "Mailcycle", package: "mailcycle")]
),
]
)
The product is Mailcycle, and the package identity is mailcycle, taken from the last part of the URL. In Xcode, use File → Add Package Dependencies… and paste the same URL.
The package pulls in one dependency of its own, Apple’s swift-crypto, for the encryption primitives. That matters because Mailcycle stores mail encrypted with keys derived from your recovery phrase, and the SDK derives them on your machine. You don’t need any of that to send, but it’s what lets the same client open the replies later.
Step 2: Authenticate with an API key or a recovery phrase
There are two ways to build a client, and they suit different places.
An API key is for servers and scripts. It’s a bearer token, it has no expiry date, and it works until you revoke it:
import Foundation
import Mailcycle
let env = ProcessInfo.processInfo.environment
let mc = try await Mailcycle.withAPIKey(env["MAILCYCLE_API_KEY"]!)
That client can send, list your addresses and manage metadata. It can’t open mail, because the keys that open mail are derived from your recovery phrase, and a key alone doesn’t carry them. To read replies too, pass the phrase as well:
let mc = try await Mailcycle.withAPIKey(
env["MAILCYCLE_API_KEY"]!,
phrase: env["MAILCYCLE_PHRASE"] // nil for a send-only client
)
With both, the SDK checks the phrase against the key’s account before it opens anything. The phrase never leaves the process. Nothing derived from it is sent to the API. The encryption guide explains what’s sealed and what isn’t.
A recovery-phrase session is the other route: Mailcycle.signIn(phrase:) runs the same challenge-and-proof handshake the Mailcycle apps use, so nothing secret crosses the wire. Sessions last 30 days. Keep mc.sessionToken somewhere private and pick it up with Mailcycle.resume(sessionToken:phrase:) rather than signing in on every run. The authentication docs cover both, and what a key can’t do (manage keys, pair devices, delete the account).
For a server that sends mail, use the API key, and add the phrase only if that server also needs to read replies. Treat the phrase as the master key to the account: keep it in your secret manager next to the API key, never in the repository.
Step 3: Choose the address you send from
from must be an address on your account. To see the ones you have:
for address in try await mc.addresses.list() {
print(address.emailAddress, address.receives ? "receives" : "send only")
}
To create one that also receives mail, so customers can reply to it, the client needs the phrase. The address’s public key is derived from it and uploaded with the request, so the mail server can seal incoming mail to that key:
let address = try await mc.addresses.create(NewAddress(prefix: "receipts", label: "Order receipts"))
print(address.emailAddress) // receipts-x7k2@...
With prefix, the server adds a short random ending. On Scale you can choose the whole name with localPart, like hello, or set style: (.person, .business, .team) to have the server roll one. The label is sealed on your machine before it’s sent.
For transactional mail, an address on your own domain is the natural choice, so receipts come from receipts@yourdomain.com rather than a shared domain. Scale includes up to 10 domains; your own domains covers the DNS steps. The email addresses guide has every option for create.
Step 4: Send your first email with async/await
Here’s a complete main.swift for a command-line target. Top-level await works in main.swift, so there’s no @main boilerplate:
import Foundation
import Mailcycle
let env = ProcessInfo.processInfo.environment
let mc = try await Mailcycle.withAPIKey(env["MAILCYCLE_API_KEY"]!)
let result = try await mc.messages.send(Outgoing(
from: "alerts@yourdomain.com",
to: "you@example.com",
subject: "Nightly import finished",
text: "Imported 12,408 rows in 41 seconds. No errors."
))
print("Sent", result.messageId)
print("Copy in Sent:", result.sentCopyId ?? "none kept")
Run it:
export MAILCYCLE_API_KEY="mak_..."
swift run Notifier
send returns a SendResult. messageId is the Message-ID header the mail went out with. sentCopyId is the id of the copy filed in the address’s Sent folder, sealed like received mail, or nil when the address keeps no copy. Store messageId with your own record of the email (the order, the user, the job) if you want to match it up later.
Outgoing takes one recipient in to. To notify three people, make three calls, each with its own address. Each send counts towards your plan’s daily sending total.
Everything in the SDK is async and throws MailcycleError. The Mailcycle client is a final class that conforms to Sendable, so one instance can be shared across tasks and actors. Create it once and reuse it, rather than signing in for every message.
How to send email from a Vapor route
This is where most server-side Swift email lives. Create one client when the app boots, keep it in Vapor’s Application.storage, and use it from your handlers.
import Mailcycle
import Vapor
struct MailcycleKey: StorageKey {
typealias Value = Mailcycle
}
extension Application {
var mailcycle: Mailcycle {
get { storage[MailcycleKey.self]! }
set { storage[MailcycleKey.self] = newValue }
}
}
// configure.swift
public func configure(_ app: Application) async throws {
guard let key = Environment.get("MAILCYCLE_API_KEY") else {
fatalError("Set MAILCYCLE_API_KEY")
}
app.mailcycle = try await Mailcycle.withAPIKey(key, phrase: Environment.get("MAILCYCLE_PHRASE"))
try routes(app)
}
Now a route that sends a welcome email when someone signs up:
import Mailcycle
import Vapor
struct SignUp: Content {
let email: String
let name: String
}
func routes(_ app: Application) throws {
app.post("signups") { req async throws -> HTTPStatus in
let signUp = try req.content.decode(SignUp.self)
// ... create the user in your database first
let sent = try await req.application.mailcycle.messages.send(Outgoing(
from: "hello@yourdomain.com",
to: signUp.email,
subject: "Welcome to Acme, \(signUp.name)",
text: "Hi \(signUp.name),\n\nYour account is ready. Reply to this email if you get stuck.\n\nThe Acme team",
fromName: "Acme"
))
req.logger.info("Welcome email sent", metadata: ["messageId": .string(sent.messageId)])
return .created
}
}
fromName sets the display name on the From line, so the recipient sees “Acme” rather than a bare address. It’s one line, up to 78 characters, without quotes or angle brackets.
Two habits keep this solid in production. Send after the database write succeeds, so you never welcome a user who doesn’t exist. And if the email is not critical to the request, move it off the request path: a Vapor Queues job, or a detached Task for something minor, so a slow send never holds up the response. The client is Sendable, so handing it to a job or task is safe.
The same pattern works for password resets, sign-in links, receipts and alerts: mail you send from addresses you own to people who asked for it. Each call sends to one recipient.
How to send an HTML email in Swift
Pass html: alongside text:. The text part is required, and it’s what plain-text clients and some screen readers show, so make it a real version of the message rather than “view this in HTML”.
let name = signUp.name
.replacingOccurrences(of: "&", with: "&")
.replacingOccurrences(of: "<", with: "<")
.replacingOccurrences(of: ">", with: ">")
_ = try await mc.messages.send(Outgoing(
from: "hello@yourdomain.com",
to: signUp.email,
subject: "Welcome to Acme",
text: "Hi \(signUp.name),\n\nYour account is ready: https://acme.example/start\n\nThe Acme team",
html: """
<p>Hi \(name),</p>
<p>Your account is ready. <a href="https://acme.example/start">Start here</a>.</p>
<p>The Acme team</p>
""",
fromName: "Acme"
))
Escape anything a user typed before you put it in HTML, as the first lines do. A name like <a href=...> should arrive as text, not as a link in your own email. Swift’s multi-line string literals keep the template readable. For anything longer than a few lines, render it with Leaf or your template engine of choice and pass the resulting string.
How to send an email with attachments in Swift
Attachments take raw Data, and the SDK encodes them. Give a file a contentId and it becomes an inline image, shown wherever the HTML says cid: and that id:
let pdf = try Data(contentsOf: URL(fileURLWithPath: "invoice-2026-11.pdf"))
let logo = try Data(contentsOf: URL(fileURLWithPath: "logo.png"))
_ = try await mc.messages.send(Outgoing(
from: "billing@yourdomain.com",
to: "customer@example.com",
subject: "Your invoice for November",
text: "Your invoice is attached.",
html: #"<img src="cid:logo" alt="Acme" width="120"><p>Your invoice is attached.</p>"#,
fromName: "Acme Billing",
attachments: [
OutgoingAttachment(filename: "invoice-2026-11.pdf", content: pdf, mimeType: "application/pdf"),
OutgoingAttachment(filename: "logo.png", content: logo, mimeType: "image/png", contentId: "logo"),
]
))
mimeType defaults to application/octet-stream, so set it for anything the recipient should open in place. A message carries up to ten files, 3.5 MB between them. The SDK refuses more than that before making the request, and program and script files such as .exe and .js are refused by the API. The Sent copy keeps the files, sealed like everything else. The sending guide lists the filename rules.
The #"..."# raw string saves escaping the quotes in the HTML. In a real invoice flow the PDF usually comes from memory rather than disk: if you generate it with a PDF library, pass its Data straight in.
How to send email from an iOS app without MFMailComposeViewController
On iOS, the built-in option is MFMailComposeViewController. It’s the right tool when you want the person to send an email from their account, such as “Contact support” with a prefilled subject. It presents a compose sheet, the person has to tap Send, and it only works when they’ve set up Mail on the device (canSendMail() tells you).
When the app itself should send (a receipt, a data export, a report), the mail has to go out with a credential that can send. And that credential must not live in the app. Anything compiled into an app you distribute can be extracted from it, and an API key or a recovery phrase gives access to the whole account.
So the pattern is: the app calls your backend, and the backend sends. The app holds only its own sign-in token for your service, which you already have.
Here’s the SwiftUI side. Note there’s no Mailcycle import at all:
import SwiftUI
struct ExportRequest: Encodable {
let reportId: String
}
struct EmailReportButton: View {
let reportId: String
let accessToken: String // your app's own sign-in token, not a Mailcycle credential
@State private var state = "Email me this report"
@State private var sending = false
var body: some View {
Button(state) {
Task { await emailReport() }
}
.disabled(sending)
}
private func emailReport() async {
sending = true
defer { sending = false }
var request = URLRequest(url: URL(string: "https://api.yourapp.com/reports/email")!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
request.httpBody = try? JSONEncoder().encode(ExportRequest(reportId: reportId))
do {
let (_, response) = try await URLSession.shared.data(for: request)
let status = (response as? HTTPURLResponse)?.statusCode ?? 0
state = status == 202 ? "Sent. Check your inbox" : "Couldn't send. Try again"
} catch {
state = "You're offline. Try again"
}
}
}
And the Vapor route it calls. The important line is where the recipient comes from: the signed-in user’s own record, never the request body. If the app could name any recipient, anyone holding a token could use your server to send mail to strangers.
app.post("reports", "email") { req async throws -> HTTPStatus in
let user = try req.auth.require(User.self) // your own authentication
let body = try req.content.decode(ExportRequest.self)
let pdf = try await Reports.renderPDF(body.reportId, for: user) // your own code, returns Data
_ = try await req.application.mailcycle.messages.send(Outgoing(
from: "reports@yourdomain.com",
to: user.email, // from your database, not the client
subject: "Your report",
text: "Your report is attached.",
fromName: "Acme",
attachments: [
OutgoingAttachment(filename: "report.pdf", content: pdf, mimeType: "application/pdf"),
]
))
return .accepted
}
The same server can share Swift types with the app. Put ExportRequest in a small shared package that both targets depend on, and the request body can’t drift between client and server.
There’s one case where Mailcycle itself runs on the device: a tool for your own use, where the person holding the phone owns the Mailcycle account. The package supports iOS 16, and Mailcycle.signIn(phrase:) works there with a phrase the person types in at runtime. Keep what you store in the Keychain. That’s a personal tool, though, not a pattern for an app you ship to customers.
How to reply to an email in the same thread
Sending from an address that receives mail means people can answer you, and Mailcycle keeps those answers in the same inbox. That’s the difference from a send-only API: you can carry on the conversation from Swift.
To reply, fetch the message you’re answering and pass it as replyTo:
let original = try await mc.messages.get(messageId)
if original.opened {
_ = try await mc.messages.send(Outgoing(
from: "support@yourdomain.com",
to: original.replyTo,
subject: original.subject.hasPrefix("Re:") ? original.subject : "Re: \(original.subject)",
text: "Thanks, we've got it. We'll get back to you today.",
replyTo: original
))
}
replyTo: original sends two fields with the request: inReplyTo, Mailcycle’s id for the message, and inReplyToHeader, the original’s Message-ID header. That second one is what Gmail, Outlook and Apple Mail use to thread the reply under the original. Send to: original.replyTo, not original.fromAddress: it’s the sender’s Reply-To when they set one, and their From address otherwise.
get needs the phrase on the client, since it opens the message. A message that won’t open, because the phrase is missing or wrong, comes back with opened == false and empty fields rather than throwing, hence the check.
Where does messageId come from? From a webhook, covered next, or from mc.messages.all(address.id) when you list an inbox. The reading mail guide covers folders, pages and read state.
How to wait for a reply in Swift
Sometimes the code that sends also needs the answer: an approval before a deploy, a confirmation from a supplier, a verification email in a test. waitFor blocks (asynchronously) until a matching message arrives, and returns it opened:
let since = Date() // take the time before sending
_ = try await mc.messages.send(Outgoing(
from: address.emailAddress,
to: "ops@example.com",
subject: "Approve deploy 412?",
text: "Reply YES to approve."
))
do {
let answer = try await mc.messages.waitFor(WaitFor(
addressId: address.id,
from: "ops@example.com",
subject: "deploy 412",
timeout: 600,
since: since
))
let approved = answer.text.lowercased().hasPrefix("yes")
print(approved ? "Approved" : "Not approved", "by", answer.fromAddress)
} catch let error as MailcycleError where error.code == "timeout" {
print("No answer in ten minutes")
}
from and subject match case-insensitively on “contains”, so “Re: Approve deploy 412?” matches "deploy 412". timeout is in seconds, and defaults to 60.
Take since before sending. Mail received from that moment on counts, even if it lands before the wait starts listening, so a fast reply is never missed. Under the hood, waitFor listens on the event stream and, if the stream can’t be reached, checks the address every five seconds instead. That’s why addressId is worth passing.
The same call makes sign-up flows testable. In an XCTest or Swift Testing case, create a fresh address, drive your sign-up screen with it (with XCUITest, or by calling your API), and pull the code out of the email:
let inbox = try await mc.addresses.create(NewAddress(prefix: "signup-test", label: "UI test"))
// ... sign up with inbox.emailAddress
let email = try await mc.messages.waitFor(WaitFor(addressId: inbox.id, subject: "verify", timeout: 90))
let code = email.text.range(of: #"\b\d{6}\b"#, options: .regularExpression).map { String(email.text[$0]) }
try await mc.addresses.delete(inbox.id)
If nothing arrives, waitFor throws with the code timeout, so the test fails with a reason instead of hanging.
How to receive email in Vapor with webhooks
For a long-running server, a webhook is better than waiting: Mailcycle calls your URL when mail arrives. Add one in the app under API → Webhooks, choose message.received, and keep the whsec_ secret it shows once. Webhooks are on Operator and above, so Scale has them.
Events carry ids, never content. Verify the signature on the raw body, then fetch and open the message yourself:
app.post("hooks", "mailcycle") { req async throws -> HTTPStatus in
// The body exactly as it arrived, before any parsing.
let raw = req.body.data.map { [UInt8]($0.readableBytesView) } ?? []
let signature = req.headers.first(name: "Mailcycle-Signature")
guard verifyWebhookSignature(secret: webhookSecret, rawBody: raw, header: signature) else {
return .unauthorized
}
let event = try JSONValue.parse(raw) // the SDK's JSON type, for payloads of any shape
if event["type"].string == "message.received", let id = event["payload"]["messageId"].string {
let message = try await req.application.mailcycle.messages.get(id)
req.logger.info("Mail from \(message.fromAddress): \(message.subject)")
// ... hand it to your support queue, or reply as above
}
return .noContent
}
webhookSecret comes from your environment, like the API key. Check the signature before parsing: a body that has been parsed and re-encoded won’t match, and the check also refuses a signature more than five minutes old. When rendering a message’s HTML anywhere, use message.safeHTML, which has remote images and other tracking removed, rather than message.html. The webhooks guide lists every event type and how retries work.
For a script or a macOS utility that runs only while it’s open, mc.events.stream() gives the same events over a live connection, as an AsyncSequence you for try await over.
Handling errors when sending email in Swift
Everything throws one type, MailcycleError. An API failure is .api(status:code:message:), with the HTTP status and the API’s stable code. Match on the code, never the message:
func sendSafely(_ mc: Mailcycle, _ outgoing: Outgoing) async throws -> SendResult? {
do {
return try await mc.messages.send(outgoing)
} catch let error as MailcycleError {
switch error.code {
case "invalid_address":
print("That recipient address isn't valid:", outgoing.to)
case "not_your_address":
print("\(outgoing.from) isn't an address on this account")
case "plan_required":
print("Sending with an API key needs the Scale plan or above")
case "daily_send_limit":
print("Today's sends are used up; sending resumes at 00:00 UTC")
case "attachment_blocked", "attachments_too_large", "too_many_attachments", "message_too_large":
print("The attachments were refused:", error)
default:
throw error
}
return nil
}
}
error.code and error.status read the fields without a switch on the enum. Requests that never got an answer have status 0 and the code network_error.
Some failures are worth retrying: 429 rate_limited, and 5xx errors such as send_failed or maintenance. Back off between attempts:
func sendWithRetry(_ mc: Mailcycle, _ outgoing: Outgoing, attempts: Int = 4) async throws -> SendResult {
var attempt = 1
var delay: Double = 2
while true {
do {
return try await mc.messages.send(outgoing)
} catch let error as MailcycleError {
let status = error.status ?? 0
let retryable = error.code == "rate_limited" || (status >= 500 && error.code != "sending_paused")
guard retryable, attempt < attempts else { throw error }
try await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000))
attempt += 1
delay *= 3
}
}
}
sending_paused is left out because it lasts until 00:00 UTC, so a few seconds’ wait won’t help. network_error is left out on purpose too: the request may have reached the API before the connection dropped, and retrying could send the email twice. Decide per message whether a duplicate or a missing email is worse. The errors reference lists every code, and rate limits explains how sending is metered.
In Vapor, turn the error into a response your own clients understand rather than leaking the API’s message:
do {
_ = try await req.application.mailcycle.messages.send(outgoing)
} catch let error as MailcycleError where error.code == "invalid_address" {
throw Abort(.unprocessableEntity, reason: "That email address doesn't look right.")
} catch let error as MailcycleError {
req.logger.error("Mailcycle send failed: \(error)")
throw Abort(.badGateway, reason: "We couldn't send the email. Try again shortly.")
}
The raw HTTP call, with cURL
The SDK is a thin layer over one HTTPS request. Here’s the same send with cURL, which is handy for checking a key or debugging from a terminal:
curl https://api.mailcycle.email/messages/send \
-H "Authorization: Bearer $MAILCYCLE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"from": "receipts@yourdomain.com",
"to": "customer@example.com",
"subject": "Your receipt",
"text": "Thanks for your order."
}'
{ "sent": true, "messageId": "<…>", "sentCopyId": "msg_…" }
You could make this call with URLSession and Codable yourself, and for sending alone that works. What the SDK adds is the other half: deriving the keys from your phrase, creating addresses that receive mail, opening what arrives, base64 for attachments, threading headers from a Message, and the stream-or-poll logic in waitFor. The developers page has the full API surface.
MFMailComposeViewController vs SwiftSMTP vs an email API
Each of these is the right answer to a different question:
MFMailComposeViewController |
SwiftSMTP (SMTP library) | Mailcycle Swift SDK | |
|---|---|---|---|
| Who sends | The person, from their own Mail account | Your code, through an SMTP server | Your code, from an address on your account |
| Needs a tap on Send | Yes | No | No |
| Runs on | iOS and iPadOS, with Mail set up | macOS and Linux | macOS 13, iOS 16 and Linux |
| Works server-side (Vapor, Hummingbird) | No | Yes | Yes |
| What you manage | Nothing; it’s the person’s account | An SMTP host, username and password | An API key, and the recovery phrase to read mail |
| Receiving replies | In the person’s own inbox | Separately, through IMAP | Same inbox, read from Swift with waitFor or webhooks |
| Threaded replies | Up to the person | Set the headers yourself | replyTo: message fills them in |
| Stored mail | In the person’s mailbox | Wherever your mail provider keeps it | Encrypted, opened with keys derived on your machine |
Use MFMailComposeViewController for “email us” buttons, where the person should write from their own address and see what they’re sending. SwiftSMTP suits a server that already has an SMTP account to send through and only needs to send. Use an email API like Mailcycle when your code sends from addresses you own and you want the replies back in Swift too.
Email for AI agents written in Swift
If your Swift code drives an AI agent, the same client gives it an inbox: it can create an address, waitFor a message, read it and reply in the thread. Mailcycle also has dedicated AI agents, paired to the account with their own credential and a send mode that starts reply-only, so an agent can answer people who wrote to it and no one else. The AI agents guide covers send modes, and the Claude Code email tutorial shows the MCP route for Claude Code, Cursor, Codex or any other MCP client.
Next steps
You can now send email from Swift on a server, from a CLI and, through your backend, from an iOS app, with HTML, attachments, threaded replies and the answers coming back. From here:
- Move sending to your own domain so mail comes from
@yourdomain.com: your own domains. - Wire up a webhook for
message.receivedso replies reach your support queue: webhooks. - Read the full Swift reference: sessions, pagination, events and pairing devices from a script, in the Swift SDK guide.
- Manage keys properly: create one key per service and revoke it when it retires. See API keys.
- Compare plans when the trial ends, on the pricing page.
Working across languages? The hub post on how to send email from any language links every guide in the series, including C# and Java.
FAQ
How do I send an email from Swift without opening the Mail app?
Send it from code that calls an email API instead of presenting MFMailComposeViewController. With the Mailcycle package, try await mc.messages.send(Outgoing(from:to:subject:text:)) sends straight away from an address on your account, with no compose sheet and no tap on Send.
Can an iOS app send email in the background?
Not safely on its own, because the app would need a credential that sends mail, and anything compiled into an app can be pulled back out of it. Have the app call your own backend, and let the backend send with a Mailcycle API key kept in its environment. The app only ever holds your own sign-in token.
How do I send email from Vapor?
Add the Mailcycle package next to Vapor, create one client in configure(_:) with Mailcycle.withAPIKey(_:phrase:), keep it in app.storage, and call messages.send from your route handlers. Sending with an API key needs the Scale plan or above, which the free 7-day trial includes.
Is there a Swift email library that works on Linux?
Yes. The Mailcycle package needs Swift 5.9 or later and runs on Linux as well as macOS 13 and iOS 16, so the same code works in a Vapor or Hummingbird server deployed in a Linux container. It uses async and await throughout.
Do I need an SMTP server to send email from Swift?
No. Foundation has no SMTP client, so the usual routes are an SMTP library such as SwiftSMTP plus a mail account to send through, or an HTTPS email API. Mailcycle is the second kind: one authenticated POST /messages/send, which the Swift SDK makes for you.
How do I send an HTML email with an attachment in Swift?
Pass html: alongside text: in Outgoing, and add OutgoingAttachment(filename:content:mimeType:) values with the file as Data. Give an image a contentId and refer to it as cid: in the HTML to show it inline. The Swift SDK guide has the details.
How do I reply to an email in the same thread from Swift?
Fetch the message you are answering, then send with to: original.replyTo and replyTo: original. The SDK fills in the threading headers, so the reply lands in the same conversation in Gmail, Outlook and Apple Mail.
How do I read the reply to an email I sent from Swift?
Take the time just before you send, then call mc.messages.waitFor(WaitFor(addressId:from:since:)). It listens on the event stream, falls back to polling, and returns the reply already decrypted. Opening mail needs your recovery phrase on the machine running the code.
Is it safe to put an email API key in my iOS app?
No. Never ship an API key or a recovery phrase in an app you distribute, because either one gives access to the account. Keep the key on a server you control and have the app call that server.
Related
Send email from any language
- Send Email with an API: Code Examples in TypeScript, Python, C#, Go, Rust, PHP, Java, Ruby and Swift (Overview: every language)
- How to Send Email from C# and an ASP.NET Core Web API (C# / .NET)
- How to Send Email from Go (Golang): HTML Templates, a Mailer Package and an API (Go)
- How to Send Email from Java: A Plain Java Program, Spring Boot, HTML, Attachments and Replies (Java / Spring Boot)
- How to Send Email from PHP with an API (Laravel and Plain PHP) (PHP / Laravel)
- How to Send Email from Python with an API: Scripts, FastAPI and Django (Python)
- How to Send Email from Ruby and Rails with an Email API (Ruby / Rails)
- How to Send Email from Rust with an API: HTML, Attachments, Axum and Replies (Rust)
- How to Send Email from Node.js and TypeScript (Express and Next.js) (TypeScript / Node.js)