Swift SDK
A Swift client for the API that does the encryption the Mailcycle apps do, on your machine. With it a program can create addresses that receive mail, open what arrives, and send. The recovery phrase never leaves the machine it runs on.
It needs Swift 5.9 or later, on macOS 13, iOS 16 or Linux.
dependencies: [ .package(url: "https://mailcycle.email/swift/mailcycle.git", from: "0.1.0"),],targets: [ .target(name: "MyTool", dependencies: [.product(name: "Mailcycle", package: "mailcycle")]),]Sign in
Section titled “Sign in”import Mailcycle
let environment = ProcessInfo.processInfo.environmentlet mc = try await Mailcycle.signIn(phrase: environment["MAILCYCLE_PHRASE"]!)This is the same handshake the apps use: nothing secret crosses the wire, and it works on every plan.
With an API key instead, on Operator and up:
let mc = try await Mailcycle.withAPIKey( environment["MAILCYCLE_API_KEY"]!, phrase: environment["MAILCYCLE_PHRASE"] // nil to manage without opening mail)Without the phrase a client can manage addresses, devices and metadata, but cannot open mail or create an address that receives it, because the address’s key is derived from the phrase. With both, the phrase is checked against the key’s account before anything is opened.
Each signIn opens a 30-day session. Keep mc.sessionToken somewhere private and pick it up with Mailcycle.resume(sessionToken:phrase:) rather than signing in on every run.
Addresses
Section titled “Addresses”let address = try await mc.addresses.create(NewAddress(prefix: "signup", label: "Test run 42"))
let all = try await mc.addresses.list()The public half of the address’s key goes up with the request so the mail server can seal what arrives; the private half stays on your machine. The label is sealed locally, and the server stores it as ciphertext.
With no prefix or localPart, the server rolls a name like quiet_falcon. Set style to choose the kind:
let address = try await mc.addresses.create(NewAddress(style: .person)) // maya.holtThe styles are .person, .business, .team and .neutral, the default. style is ignored when prefix or localPart is set.
To pick a name before creating, roll a few:
let names = try await mc.addresses.rollNames(style: .business) // up to 8, like harbor-supply42
let address = try await mc.addresses.create(NewAddress(localPart: names[0]))A rolled name works as localPart on every plan; any other name needs Scale and up. The names are free when rolled, but someone can take one before you create it, and then create is refused. Pass domain: to roll for a domain; leave it out to use the one create would.
Reading mail
Section titled “Reading mail”let messages = try await mc.messages.all(address.id)for message in messages { print(message.fromAddress, message.subject)}
let data = try await mc.messages.attachment(messages[0], index: 0) // Data, opened locallyA message that will not open, because there is no phrase or it is the wrong one, comes back with opened == false and empty content rather than an error, so one unreadable message does not hide the rest of a page.
message.html is the HTML as the sender wrote it. message.safeHTML has every remote image, stylesheet and embed removed, as the apps do it, and is the one to render; message.blocked lists what was taken out.
Waiting for a message
Section titled “Waiting for a message”let code = try await mc.messages.waitFor(WaitFor(addressId: address.id, subject: "verification"))Listens on the event stream where it is available and polls the address otherwise, and returns the message opened. If nothing matching arrives in time it throws MailcycleError.api with the code timeout. Mail received from since on counts, even if it landed before the stream was up; it defaults to now, so to wait for a reply to something you are about to send, take the time before sending.
Sending
Section titled “Sending”_ = try await mc.messages.send(Outgoing( from: address.emailAddress, to: "someone@example.com", subject: "Hello", text: "Hi"))Set replyTo to the message you are answering to thread a reply. A session can send from Personal up; an API key on Scale and up. Free receives only.
send returns a SendResult: messageId is the Message-ID header, and sentCopyId is the id of the copy in Sent, which the other message calls take, or nil when the address keeps none.
Attachments take raw bytes and the client encodes them. A message can carry up to ten files, 3.5 MB between them. Give a file a contentId to show it inline, where the HTML says cid: and that id. Program and script files, like .exe and .js, are refused.
let pdf = try Data(contentsOf: URL(fileURLWithPath: "invoice.pdf"))let logo = try Data(contentsOf: URL(fileURLWithPath: "logo.png"))_ = try await mc.messages.send(Outgoing( from: address.emailAddress, to: "someone@example.com", subject: "Your invoice", text: "Attached.", html: #"<img src="cid:logo"><p>Attached.</p>"#, attachments: [ OutgoingAttachment(filename: "invoice.pdf", content: pdf, mimeType: "application/pdf"), OutgoingAttachment(filename: "logo.png", content: logo, mimeType: "image/png", contentId: "logo"), ]))Events and webhooks
Section titled “Events and webhooks”let stream = try mc.events.stream()for try await event in stream.events { print(event.type)}Events carry ids, never content, and are not replayed after a drop, so Hooks.onReconnect, passed to stream(hooks:), is where to refetch what you are showing. The loop ends when you call stream.close(), and stream.next(timeout:) reads one event with a deadline.
To check a webhook came from Mailcycle, pass the body exactly as it arrived:
verifyWebhookSignature(secret: secret, rawBody: rawBody, header: header)API keys
Section titled “API keys”let created = try await mc.apiKeys.create(name: "Deploy script")print(created.token) // shown once; keep it somewhere private
for key in try await mc.apiKeys.list() { print(key.id, key.name ?? "", "...\(key.hint)")}try await mc.apiKeys.revoke(created.apiKey.id)Listing, creating and revoking keys need a signed-in session, so a leaked key cannot make more of itself. The name is sealed on your machine, and the server stores it as ciphertext. A name that will not open comes back as nil.
signOut() on a client built with an API key does nothing. A key is not a session; it works until it is revoked.
Webhooks
Section titled “Webhooks”let created = try await mc.webhooks.create( url: "https://example.com/hooks/mail", events: ["message.received"], name: "Orders")let secret = created.secret // shown once, for checking signatures
_ = try await mc.webhooks.update(created.webhook.id, WebhookUpdate(enabled: false))_ = try await mc.webhooks.test(created.webhook.id)
let page = try await mc.webhooks.deliveries(created.webhook.id)for delivery in page.deliveries { print(delivery.eventType, delivery.status, delivery.responseStatus ?? 0)}Webhooks are on Operator and up. list() returns the webhooks with their names opened, and every event type one can ask for. rotateSecret returns a new secret once, and redeliver sends a logged event again with the same event id. Adding, changing, rotating and removing need a signed-in session; an API key can list, test, read deliveries and redeliver.
Sessions
Section titled “Sessions”for session in try await mc.sessions.list() { print(session.id, session.expiresAt, session.current)}_ = try await mc.sessions.revokeOthers()revoke(_:) ends one session. All three need a signed-in session.
Deleting the account
Section titled “Deleting the account”try await mc.deleteAccount()Erases the account and everything in it at once, with no grace period. Its addresses are retired and never issued again. It needs a signed-in session. If the account balance still holds money you paid in, it is refused with balance_held: ask for the balance back through support first.
mc.subscription() returns the plan, renewal date and balance, and mc.plans() lists every plan.
Pairing devices
Section titled “Pairing devices”// The text of the device's QR code, or the eight digits it shows.let device = try await mc.devices.pair("MC1:12345678:...", name: "Kitchen Pi")
try await mc.devices.assign(device.id, addressId: address.id) // hands the keys over tootry await mc.devices.unassign(device.id, addressId: address.id)try await mc.devices.handOverKeys(device.id) // again, on its ownThis is what the app’s Add device screen does, done by a script. It needs the phrase and a signed-in session. The name is sealed on your machine.
Each device has a wrap secret, and its address keys are sealed under it. The account keeps a copy in the device’s sealed profile, so keys can be handed over again when an address is assigned or taken off.
There are two ways the secret gets here. The QR code carries the device’s own secret, so it never passes through Mailcycle. The eight digits carry no secret, so the client makes one and seals it to a key the device published. The server relays that key, so it could put its own in its place at pairing and read the keys that follow. The QR path does not have that gap. Use it where you can.
A device on an older build publishes no key. Pairing it by its digits fails with an error that says to pair it in the app, or pass its QR code instead.
Errors
Section titled “Errors”Everything throws MailcycleError. An API failure is .api(status:code:message:) carrying the HTTP status and the API’s own code, which is what to match on; error.code reads it.
How the encryption is checked
Section titled “How the encryption is checked”It is checked against the published test vectors, including the refusals.
© Northlab Studios Ltd, trading as Mailcycle. Registered in England and Wales, company no. 17462734. Registered office: 167-169 Great Portland Street, London W1W 5PF.