How to Receive Email in Rust: Read the Inbox, Save Attachments and Handle Webhooks in Axum

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

By · · 12 min read

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

You want to receive email in Rust: 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 service. lettre sends mail and does not read it, so receiving usually means an IMAP crate, 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 Rust with Mailcycle’s Rust crate, mailcycle. 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 an Axum handler by webhook.

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

Quick answer: how to receive email in Rust

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

cargo add mailcycle --features events
use std::time::Duration;

use mailcycle::{Mailcycle, NewAddress, WaitFor};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let phrase = std::env::var("MAILCYCLE_PHRASE")?;
    let mc = Mailcycle::sign_in(&phrase, Default::default())?;

    let address = mc.addresses().create(NewAddress {
        prefix: Some("inbound".into()),
        label: Some("Rust inbox".into()),
        ..Default::default()
    })?;
    println!("Send an email to {}", address.email_address);

    let message = mc.messages().wait_for(WaitFor {
        address_id: Some(&address.id),
        timeout: Duration::from_secs(300),
        ..Default::default()
    })?;
    println!("{} {}", message.from_address, message.subject);
    println!("{}", message.text);
    Ok(())
}

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 Rust SDK lists, waits for or receives it by webhook, and your Rust code reads the message
Mail sent to a Mailcycle address is encrypted on arrival, then your Rust code reads it with the Rust SDK, by waiting for it or from a webhook.

Prerequisites

  • Rust 1.75 or later. Check with rustc --version.
  • 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: axum 0.8, tokio with the full feature, and serde_json.

Step 1: Add the Rust crate

cargo add mailcycle --features events

or in Cargo.toml:

[dependencies]
mailcycle = { version = "0.6", features = ["events"] }

The events feature adds the live event stream, which wait_for uses to hear about new mail the moment it arrives. Without it, wait_for checks the address every five seconds instead.

The crate is synchronous, built on ureq, so a CLI, a cron job or a worker can use it without an async runtime. Inside Tokio, run its calls with spawn_blocking, as the webhook example does. The handles are methods on the client: mc.addresses(), mc.messages() and mc.webhooks().

Step 2: Sign in and create an address

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

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 = mc.addresses().create(NewAddress {
    prefix: Some("invoices".into()),
    label: Some("Supplier invoices".into()),
    retention_days: Some(30),
    ..Default::default()
})?;
println!("{} {}", address.email_address, address.id);

for existing in mc.addresses().list()? {
    println!("{} {:?} {}", existing.email_address, existing.label, existing.receives);
}

The fields on NewAddress:

  • prefix: Some("invoices".into()) gives invoices- plus a random ending on a shared domain.
  • style (a NameStyle) rolls a name in that style.
  • local_part 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.
  • retention_days is 1 to 90, and 7 when left as None.

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 = mc.messages().list(&address.id, None, Some(20), None)?;
for message in &page.messages {
    let flag = if message.read { " " } else { "*" };
    println!("{flag} {} {} {}", message.received_at, message.from_address, message.subject);
}

if let Some(cursor) = page.next_cursor.as_deref() {
    let older = mc.messages().list(&address.id, None, Some(20), Some(cursor))?;
    println!("{} older messages on the next page", older.messages.len());
}

The arguments are the address id, a folder (None is the inbox), a limit and a cursor. next_cursor is opaque: pass it back as it came, and it is None on the last page. To walk a whole folder, all pages for you:

let all = mc.messages().all(&address.id, Some("inbox"))?;

let invoices: Vec<_> = all
    .iter()
    .filter(|message| message.subject.to_lowercase().contains("invoice") && !message.attachments.is_empty())
    .collect();
println!("{} invoices with files attached", invoices.len());

Message content is encrypted, so you decrypt and then filter in Rust, as above. Pass Some("sent"), Some("junk"), Some("trash") or Some("starred") as the folder to read another one.

What is in a Message

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

Field What it holds
id, address_id The message’s msg_... id and the address it arrived at.
received_at When it arrived, as an RFC 3339 string in UTC.
from_address, from_name The sender’s address and display name.
reply_to 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.
safe_html The HTML with remote images, trackers and embeds removed.
attachments A Vec<Attachment>: index, filename, mime_type, size, content_id, stored.
message_id 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 Rust: text, html and safe_html

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 safe_html:

let message = mc.messages().get("msg_91be02c4a7d1")?;
if !message.opened {
    return Err("this message did not open: check the recovery phrase".into());
}

if message.text.is_empty() {
    println!("(no plain-text part)");
} else {
    println!("{}", message.text);
}

if !message.safe_html.is_empty() {
    std::fs::write("preview.html", &message.safe_html)?;
    println!("{} remote items taken out", message.blocked.len());
}

get fetches one message by id, from any folder. safe_html 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. If you embed it in a page of your own, put it in a sandboxed <iframe>.

Download email attachments in Rust

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

use std::path::{Path, PathBuf};

use mailcycle::{Mailcycle, Message};

fn save_attachments(
    mc: &Mailcycle,
    message: &Message,
    folder: &Path,
) -> Result<Vec<PathBuf>, Box<dyn std::error::Error>> {
    let target = folder.join(&message.id);
    let mut saved = Vec::new();
    for attachment in &message.attachments {
        if !attachment.stored {
            continue; // an empty part: nothing to fetch
        }
        if attachment.content_id.is_some() {
            continue; // an image the HTML shows inline, like a logo
        }

        let data = mc.messages().attachment(message, attachment.index)?; // opened on this machine
        std::fs::create_dir_all(&target)?;
        let cleaned = attachment.filename.replace('\\', "/");
        let name = Path::new(&cleaned)
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or("attachment");
        let path = target.join(format!("{}-{}", attachment.index, name));
        std::fs::write(&path, data)?;
        saved.push(path);
    }
    Ok(saved)
}

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

for message in mc.messages().all(&address.id, Some("inbox"))? {
    if message.read || message.attachments.is_empty() {
        continue;
    }
    for path in save_attachments(&mc, &message, Path::new("downloads"))? {
        println!("saved {}", path.display());
    }
    mc.messages().mark_read(&message.id, true)?;
}

The details that matter with real mail:

  • The file name comes from the sender. A name like ../../.bashrc is a classic path-traversal trick. Path::file_name 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.
  • content_id marks an inline image, the kind HTML shows with <img src="cid:logo">. Most pipelines want the PDF, not the logo.
  • mime_type 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 a Rust email parser does for attachments, without walking a MIME tree or decoding base64.

Wait for the next email in Rust

wait_for 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:

use std::time::{Duration, SystemTime};

let started = SystemTime::now(); // take the time before the email is triggered

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

let message = match mc.messages().wait_for(WaitFor {
    address_id: Some(&address.id),
    subject: Some("verify"),
    since: Some(started),
    timeout: Duration::from_secs(120),
    ..Default::default()
}) {
    Ok(message) => message,
    Err(error) if error.code() == Some("timeout") => {
        return Err("no verification email within two minutes".into());
    }
    Err(error) => return Err(error.into()),
};

let code = message
    .text
    .split(|c: char| !c.is_ascii_digit())
    .find(|part| part.len() == 6)
    .ok_or("no six-digit code in the message")?;
println!("code: {code}");

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 wait_for is called.
  • from and subject match text the sender or subject contains, ignoring case. address_id limits the wait to one address.
  • timeout is one minute by default. When it runs out you get Error::Api with code set to "timeout".
  • poll_every (five seconds by default) is how often it checks when the live stream is not available.

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

#[test]
fn reads_the_verification_email() -> Result<(), Box<dyn std::error::Error>> {
    let mc = Mailcycle::sign_in(&std::env::var("MAILCYCLE_PHRASE")?, Default::default())?;
    let address = mc.addresses().create(NewAddress {
        prefix: Some("test".into()),
        retention_days: Some(1),
        ..Default::default()
    })?;

    // ...trigger the email to address.email_address, then wait_for it...

    mc.addresses().delete(&address.id)?;
    Ok(())
}

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().mark_read(&id, true) Marks read. mark_read(&id, false) marks unread.
mc.messages().star(&id, true) Stars it. star(&id, false) unstars.
mc.messages().move_to(&id, "junk") Moves to "inbox", "junk" or "trash".
mc.messages().delete(&id) Deletes it now.

Get new email pushed to Rust 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 Rust with a signed-in session:

let created = mc.webhooks().create(
    "https://example.com/hooks/mailcycle",
    &["message.received"],
    "Inbound mail",
)?;
println!("{} {}", 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 handler, in Axum:

use std::{
    collections::HashSet,
    sync::{Arc, Mutex},
};

use axum::{
    body::Bytes,
    extract::State,
    http::{HeaderMap, StatusCode},
    routing::post,
    Router,
};
use mailcycle::{verify_webhook_signature_now, Mailcycle};

#[derive(Clone)]
struct AppState {
    mail: Arc<Mailcycle>,
    secret: Arc<str>,
    seen: Arc<Mutex<HashSet<String>>>, // one process only: use a table with a unique key in production
}

async fn mailcycle_webhook(State(state): State<AppState>, headers: HeaderMap, body: Bytes) -> StatusCode {
    // Verify the exact bytes that arrived, before any parsing.
    let signature = headers.get("Mailcycle-Signature").and_then(|value| value.to_str().ok());
    if !verify_webhook_signature_now(&state.secret, &body, signature) {
        return StatusCode::UNAUTHORIZED;
    }

    if let Some(event_id) = headers.get("Mailcycle-Event-Id").and_then(|value| value.to_str().ok()) {
        if !state.seen.lock().unwrap().insert(event_id.to_owned()) {
            return StatusCode::NO_CONTENT; // a retry of an event already handled
        }
    }

    let Ok(event) = serde_json::from_slice::<serde_json::Value>(&body) else {
        return StatusCode::BAD_REQUEST;
    };
    if event["type"] == "message.received" {
        let message_id = event["payload"]["messageId"].as_str().unwrap_or_default().to_owned();
        let mail = state.mail.clone();
        // Answer fast, then do the work on the blocking pool.
        tokio::task::spawn_blocking(move || {
            if let Err(error) = process(&mail, &message_id) {
                eprintln!("could not process {message_id}: {error}");
            }
        });
    }
    StatusCode::NO_CONTENT
}

fn process(mc: &Mailcycle, message_id: &str) -> Result<(), Box<dyn std::error::Error>> {
    let message = mc.messages().get(message_id)?; // fetched by id, opened here
    if !message.opened {
        return Ok(());
    }
    let saved = save_attachments(mc, &message, std::path::Path::new("downloads"))?;
    println!("{}: {} ({} files)", message.from_address, message.subject, saved.len());
    mc.messages().mark_read(&message.id, true)?;
    Ok(())
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mail = Mailcycle::sign_in(&std::env::var("MAILCYCLE_PHRASE")?, Default::default())?;
    let state = AppState {
        mail: Arc::new(mail),
        secret: Arc::from(std::env::var("MAILCYCLE_WEBHOOK_SECRET")?),
        seen: Arc::default(),
    };

    let app = Router::new().route("/hooks/mailcycle", post(mailcycle_webhook)).with_state(state);
    let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await?;
    axum::serve(listener, app).await?;
    Ok(())
}

save_attachments 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. verify_webhook_signature_now checks it in constant time and refuses a timestamp more than five minutes old. Take the body as Bytes, not Json<...>: a body that was decoded and re-encoded will not match.
  • Answer fast. Mailcycle waits 10 seconds for a 2xx. The handler replies first and does the fetching and saving on the blocking pool, because the crate’s calls block.
  • Deduplicate. An event can arrive more than once, and Mailcycle-Event-Id is the same on every attempt. The HashSet suits one process. With several instances, insert the id into a table with a unique constraint.
  • Actix Web and Rocket follow the same steps: read the raw body, verify, fetch by id.

You can test the handler without a live webhook. webhook_signature_header(secret, body, 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.

A blocking client inside an async Rust service

The client calls are blocking: each one returns a Result when the request finishes. In a plain binary or a test that is exactly what you want. In a Tokio service, run them on the blocking pool so they never stall the async runtime.

use std::sync::Arc;

let mc = Arc::new(Mailcycle::sign_in(&std::env::var("MAILCYCLE_PHRASE")?, Default::default())?);

let message = tokio::task::spawn_blocking({
    let mc = Arc::clone(&mc);
    let address_id = address.id.clone();
    move || {
        mc.messages().wait_for(WaitFor {
            address_id: Some(&address_id),
            timeout: Duration::from_secs(60),
            ..Default::default()
        })
    }
})
.await??;

The double ? unwraps the join error first and the SDK error second. Wrapping the client in an Arc lets several handlers share one signed-in session, which is cheaper than signing in per request. A webhook handler in Axum can use the same trick to fetch and open a message after verifying the signature, as in the handler above.

Clean up addresses with a Drop guard

Rust’s ownership model gives you a tidy way to guarantee a test address is deleted, even when an assertion panics halfway through. Wrap the address in a small struct that deletes it when it goes out of scope.

struct TestAddress<'a> {
    mc: &'a Mailcycle,
    id: String,
    email: String,
}

impl<'a> TestAddress<'a> {
    fn new(mc: &'a Mailcycle) -> Result<Self, mailcycle::Error> {
        let a = mc.addresses().create(NewAddress {
            prefix: Some("test".into()),
            retention_days: Some(1),
            ..Default::default()
        })?;
        Ok(Self { mc, id: a.id, email: a.email_address })
    }
}

impl Drop for TestAddress<'_> {
    fn drop(&mut self) {
        let _ = self.mc.addresses().delete(&self.id);
    }
}

A test that holds a TestAddress never leaks an inbox, and the one day retention is a second safety net if the process is killed before drop runs.

Typed errors with thiserror

The SDK returns mailcycle::Error, and error.code() gives the API’s error code as an Option<&str>. In an application, fold it into your own error type so callers can match on what went wrong.

#[derive(Debug, thiserror::Error)]
enum InboxError {
    #[error("no email within the wait")]
    Timeout,
    #[error("rate limited, back off")]
    RateLimited,
    #[error(transparent)]
    Mailcycle(#[from] mailcycle::Error),
}

fn classify(e: mailcycle::Error) -> InboxError {
    match e.code() {
        Some("timeout") => InboxError::Timeout,
        Some("rate_limited") => InboxError::RateLimited,
        _ => InboxError::Mailcycle(e),
    }
}

With that in place a retry loop can back off on RateLimited, report Timeout to a user, and let anything else bubble up with its context.

Cargo features, MSRV and CI

Add features = ["events"] only if you use the live event stream, because leaving it off keeps the WebSocket dependency out of your build. Run the live test in CI behind an ignore attribute and a dedicated job: cargo test -- --ignored runs the tests that need a recovery phrase, and a plain cargo test stays offline. Store MAILCYCLE_PHRASE as a CI secret, and keep retention_days at 1 on every test address so the account stays tidy. If your crate declares a minimum supported Rust version, build with it in a separate CI job, since the SDK pulls in its own dependencies and a pinned toolchain shows early when one of them moves forward.

Axum state for a shared client

In an Axum service, put the client in the application state behind an Arc and clone the Arc into each handler through State. Because the calls block, wrap them in spawn_blocking inside the handler, or build a small worker thread that receives jobs over a channel and owns the client. The second shape fits a service that reads mail on a schedule, since the blocking work never touches the async runtime at all.

An IMAP crate and an email API in Rust

Rust has no IMAP client in the standard library. Crates such as imap and async-imap connect to a mailbox: you give them a host, port 993 and credentials, select the inbox, fetch messages and parse the MIME with a crate such as mailparse.

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 crate such as imap Mailcycle Rust crate
Install An IMAP crate, a TLS crate and a MIME parser cargo add mailcycle --features events
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 fields: text, html, attachments
Tracker-free HTML Strip it yourself safe_html, 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 wait_for()
Mail at rest Depends on the provider Encrypted with keys from your recovery phrase

Troubleshooting

  • 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::sign_in(&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() returns Some("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.
  • wait_for blocks your Tokio worker. The crate is synchronous. Run it inside tokio::task::spawn_blocking.
  • The webhook handler 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 code is listed in Errors.

Reply from Rust, or hand the inbox to an agent

To answer a message in the same thread, set reply_to: Some(&message) on an Outgoing and call mc.messages().send(). Sending email from Rust 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 Rust?

Give your program an address that receives mail, then read it with a client. With Mailcycle, run cargo add mailcycle --features events, sign in with Mailcycle::sign_in(&phrase, Default::default()), create an address with mc.addresses().create(NewAddress::default()), and call mc.messages().wait_for(WaitFor::default()). The message comes back parsed and decrypted: sender, subject, text, HTML and attachments.

How do I read emails from an inbox in Rust?

Call mc.messages().list(&address_id, None, Some(20), None) for one page, newest first, or mc.messages().all(&address_id, Some("inbox")) to walk the whole folder. Each Message has from_address, subject, text, safe_html, attachments and read.

How do I download email attachments in Rust?

Each Message lists its files in message.attachments, with filename, mime_type, size and index. Call mc.messages().attachment(&message, attachment.index) to get a Vec<u8>, opened on your machine, and write it with std::fs::write. Take only the last part of the file name first, because it comes from the sender.

How can a Rust program wait for a new email?

Call mc.messages().wait_for(WaitFor { address_id: Some(&id), subject: Some("verify"), ..Default::default() }). It returns the first matching message. If nothing matches in time it returns Error::Api with code set to "timeout", which error.code() reads for you.

How do I get notified when an email arrives in an Axum service?

Add a webhook for message.received, point it at an Axum handler that takes the body as Bytes, and check each delivery with verify_webhook_signature_now() 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 Rust crate to read email without IMAP?

Yes. The mailcycle crate 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 Rust?

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 Rust client need my recovery phrase?

Mail is encrypted the moment it arrives, with keys from your recovery phrase. The Rust 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