mailcycle 0.8.0

Rust email API client: create addresses that receive email, read and decrypt messages on your machine, send email, verify webhooks and stream events.
Documentation
# mailcycle

A Rust client for the Mailcycle API that does the encryption on your machine. Create addresses that receive mail, read what arrives, send, and listen for events. Mailcycle stores mail sealed to keys derived from your recovery phrase, and this crate derives them locally; the phrase never leaves your machine.

Home page and examples: https://mailcycle.email/sdks/rust/

Guide: https://docs.mailcycle.email/guides/sdk-rust/

Needs Rust 1.75 or later.

```toml
[dependencies]
mailcycle = { version = "0.6", features = ["events"] }   # "events" adds the live stream
```

## Sign in

```rust
use mailcycle::Mailcycle;

// With the recovery phrase: everything the app can do, on any plan.
let mut mc = Mailcycle::sign_in(&std::env::var("MAILCYCLE_PHRASE")?, Default::default())?;

// With an API key (Operator and up). Add the phrase to open mail and create
// addresses that receive it.
let scripted = Mailcycle::with_api_key(
    &std::env::var("MAILCYCLE_API_KEY")?,
    std::env::var("MAILCYCLE_PHRASE").ok().as_deref(),
    Default::default(),
)?;
```

Signing in uses the same handshake as the app: the server sends a challenge and the client proves it holds the key, so nothing secret crosses the wire. With an API key and a phrase, the phrase is checked against the key's account before anything is opened.

Each `sign_in` opens a 30-day session. Keep `mc.session_token()` somewhere private and pick it up with `Mailcycle::resume(token, phrase, options)` rather than signing in on every run. `Mailcycle::create_account(None, options)` makes a new account and returns the client and its phrase; keep the phrase, because nothing can recover the account without it.

One account covers every device and agent you run. Make it once, then pair each device to it or give each one its own address, as [Pair many devices](https://docs.mailcycle.email/guides/pair-many-devices/) shows. Paid plans pair as many devices as you have, and [Fleet](https://mailcycle.email/pricing) is built for device fleets at scale.

## Addresses that receive mail

```rust
use mailcycle::NewAddress;

let address = mc.addresses().create(NewAddress {
    prefix: Some("signup".into()),
    label: Some("Test run 42".into()),
    ..Default::default()
})?;
println!("{}", address.email_address);
```

The address's public key is derived from the phrase and sent with it, so the mail server can seal what arrives. The label is sealed on your machine, and the server stores it as ciphertext.

## Exporting and rotating an address key

```rust
let exported = mc.addresses().export_key(&address.id, None)?;   // current epoch; Some(n) for an earlier one
println!("{} {}", exported.private_key, exported.public_key);   // base64url

let (address_id, epoch) = mc.addresses().rotate_key(&address.id)?;
```

`export_key` returns the address's private key (base64url) at a key epoch, from 0 to the address's current one. It opens that address's mail and nothing else, which is what a helper such as the [decrypt Worker](https://docs.mailcycle.email/guides/decrypt-worker/) for n8n, Make, Zapier and Pipedream needs. Treat it like the address's mail. Each export is recorded in the account history before the key is returned, and the key is derived on your machine. It needs the phrase and a signed-in session, and an epoch above the current one is refused with `invalid_epoch`.

`rotate_key` moves the address to its next key epoch, so an exported key stops opening new mail. A device or agent holding the address is handed the new key. An address shared with team members is refused with `team_address`: give it new keys in the web app, which also gives each member the new key. Available from 0.7.0.

## Reading mail

```rust
for message in mc.messages().all(&address.id, None)? {
    println!("{} {}", message.from_address, message.subject);
}

let data = mc.messages().attachment(&message, 0)?;   // Vec<u8>, opened locally
```

A 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, remote images and all. `message.safe_html` has everything remote removed, the same way the app does it, and is the one to render; `message.blocked` says what was taken out and who it would have reported to.

## Waiting for mail

```rust
use mailcycle::WaitFor;

let code = mc.messages().wait_for(WaitFor {
    address_id: Some(&address.id),
    subject: Some("verification"),
    ..Default::default()
})?;
```

Listens on the event stream and returns the next matching message, opened. Where the stream is not available (a build without the `events` feature) it checks the address every five seconds instead, so `address_id` is needed then. If nothing arrives in time it returns an `Error::Api` with `code = "timeout"`.

Mail received from `since` on counts, including mail that landed before the stream was up. It defaults to when `wait_for` is called; to wait for a reply, set it to just before the send, so a fast reply is not missed. Five seconds are allowed for the difference between this clock and the server's.

```rust
let since = std::time::SystemTime::now();
mc.messages().send(Outgoing::new(&address.email_address, "bot@example.com", "Hello", "Hi"))?;
let reply = mc.messages().wait_for(WaitFor {
    address_id: Some(&address.id),
    since: Some(since),
    ..Default::default()
})?;
```

## Sending

```rust
use mailcycle::Outgoing;

mc.messages().send(Outgoing::new(
    &address.email_address,
    "someone@example.com",
    "Hello",
    "Hi",
))?;

mc.messages().send(Outgoing {
    reply_to: Some(&message),      // fills in the threading headers
    ..Outgoing::new(&address.email_address, &message.reply_to, "Re: Hello", "Thanks")
})?;
```

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 `content_id` to show it inline, where the HTML says `cid:` and that id. Program and script files, like `.exe` and `.js`, are refused.

```rust
use mailcycle::OutgoingAttachment;

let pdf = std::fs::read("invoice.pdf")?;
let logo = std::fs::read("logo.png")?;
let files = [
    OutgoingAttachment { mime_type: Some("application/pdf"), ..OutgoingAttachment::new("invoice.pdf", &pdf) },
    OutgoingAttachment {
        mime_type: Some("image/png"),
        content_id: Some("logo"),
        ..OutgoingAttachment::new("logo.png", &logo)
    },
];
mc.messages().send(Outgoing {
    html: Some(r#"<img src="cid:logo"><p>Attached.</p>"#),
    attachments: &files,
    ..Outgoing::new(&address.email_address, "someone@example.com", "Your invoice", "Attached.")
})?;
```

A session can send from Personal up; an API key on Scale and up. Free receives only. Limits are in the [rate limits](https://docs.mailcycle.email/reference/rate-limits/).

`send` returns a `SendResult`: `message_id` is the Message-ID header, and `sent_copy_id` is the id of the copy in Sent, which the other message calls take.

## Events

```rust
let stream = mc.events().stream()?;
while let Some(event) = stream.next_event(None) {
    println!("{} {:?}", event.event_type, event.payload);
}
```

The same events as webhooks, the moment they happen, and they carry ids rather than content. The stream reconnects after a drop, and events that happen while it is down are not replayed, so `Hooks::on_reconnect` is where to refetch whatever you are showing.

To check a webhook came from Mailcycle, pass the body exactly as it arrived, before any parsing:

```rust
use mailcycle::verify_webhook_signature_now;

verify_webhook_signature_now(secret, raw_body, header);
```

## API keys

```rust
let created = mc.api_keys().create("Deploy script")?;
println!("{}", created.token);   // shown once; keep it somewhere private

for key in mc.api_keys().list()? {
    println!("{} {:?} ...{}", key.id, key.name, key.hint);
}
mc.api_keys().revoke(&created.api_key.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 `None`.

`sign_out()` on a client built with an API key does nothing. A key is not a session; it works until it is revoked.

## Webhooks

```rust
use mailcycle::WebhookUpdate;

let created = mc.webhooks().create("https://example.com/hooks/mail", &["message.received"], "Orders")?;
let secret = created.secret;   // shown once, for checking signatures

mc.webhooks().update(&created.webhook.id, WebhookUpdate { enabled: Some(false), ..Default::default() })?;
mc.webhooks().test(&created.webhook.id)?;

let page = mc.webhooks().deliveries(&created.webhook.id, None, None)?;
for delivery in &page.deliveries {
    println!("{} {} {:?}", delivery.event_type, delivery.status, delivery.response_status);
}
```

Webhooks are on Operator and up. `list()` returns the webhooks with their names opened, and every event type one can ask for. `rotate_secret` 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

```rust
for session in mc.sessions().list()? {
    println!("{} {} {}", session.id, session.expires_at, session.current);
}
mc.sessions().revoke_others()?;
```

`revoke(id)` ends one session. All three need a signed-in session.

## Deleting the account

```rust
mc.delete_account()?;
```

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, and confirms with the phrase by answering a fresh challenge. If the account balance still holds money you paid in, it is refused with `balance_held`: ask for the balance back from Support first.

`mc.subscription()` returns the plan, renewal date and balance, and `mc.plans()` lists every plan.

## Pairing devices

```rust
// The text of the device's QR code, or the eight digits it shows.
let device = mc.devices().pair("MC1:12345678:...", "Kitchen Pi")?;

mc.devices().assign(&device.id, &address.id)?;     // hands the keys over too
mc.devices().unassign(&device.id, &address.id)?;
mc.devices().hand_over_keys(&device.id)?;          // again, on its own
```

This 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

Everything returns `Result<T, mailcycle::Error>`. An API failure is `Error::Api` carrying the HTTP `status` and the API's own `code`, such as `plan_required` or `session_required`, which is what to match on rather than the message. See [errors](https://docs.mailcycle.email/reference/errors/).

When the account's plan does not include a call (`plan_required` or `plan_capability_required`), the error also carries `required_plan_id()`, the lowest plan that allows it, and `upgrade_url()`, the page that moves the account to that plan. Its `Display` ends with the link:

```text
plan_required: API keys need the Operator plan or higher. Upgrade at https://app.mailcycle.email/operator/billing?upgrade=plan_operator
```

## How it is checked

The encryption is checked against Mailcycle's published test vectors (https://docs.mailcycle.email/vectors.json), including the refusals.

## Licence

Apache License 2.0. Copyright (c) 2026 Northlab Studios Ltd. You may use, modify and redistribute this crate, including inside your own applications, under the terms in the LICENSE file included with it. Using the Mailcycle API itself is governed by the [Terms of Service](https://mailcycle.email/legal/terms/). Never ship an API key in software you distribute.