How to Send Email from Rust with an API: HTML, Attachments, Axum and Replies

Send email from Rust with an API: one crate, no SMTP server. Plain text, HTML, attachments, an Axum handler, threaded replies and reading the answers in code.

By · · 17 min read

Rust code from this guide, in main.rs, sending or reading email with Mailcycle

If you want to send email from Rust without wiring up an SMTP server, the shortest route is an email API with a Rust crate. This tutorial shows how to send email from Rust with the Mailcycle crate, mailcycle: a plain-text message in a dozen lines, then HTML email, attachments, a real Axum endpoint with shared state, threaded replies, and reading the answers back in code.

Everything here is code that compiles against the crate’s current release (0.6.0). By the end you’ll have a small Rust service that sends transactional mail from an address you own and can pick up the replies in the same inbox, which is the part send-only APIs leave out.

To read mail as well as send it, see How to receive email in Rust: create an address, wait for a message, save attachments and handle an axum webhook.

TL;DR: how to send email in Rust

To send an email from Rust, add the mailcycle crate, create a client with an API key read from an environment variable, and call mc.messages().send() with an Outgoing built from a from address on your account, one recipient, a subject and a text body. It’s one HTTPS call: no SMTP host, port or TLS settings.

cargo add mailcycle
use mailcycle::{Mailcycle, Outgoing};

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

    let sent = mc.messages().send(Outgoing::new(
        "receipts@yourdomain.com", // an address on your account
        "customer@example.com",
        "Your order has shipped",
        "Order 1042 left our warehouse this morning.",
    ))?;

    println!("sent {}", sent.message_id);
    Ok(())
}

That’s the whole thing. The rest of this post builds it into something you’d put in production.

What you’ll build: a Rust email API client

  • A client built once from environment variables and shared across your app.
  • Plain-text and HTML email, with a display name on the From line.
  • Attachments, including an inline logo referenced from the HTML.
  • An Axum POST /welcome endpoint that sends a welcome email without blocking the Tokio executor.
  • A threaded reply, and code that waits for the recipient’s answer and reads it.
  • Error handling that matches on the API’s stable error codes, with retries where retrying helps.

The same steps exist for other languages too. See the send email from any language overview, or jump to the Go, Python or TypeScript versions.

Flow: your Rust code calls the Rust SDK, Mailcycle sends the email from your address, and the recipient gets it
Your Rust code calls the Rust SDK, and Mailcycle sends the email from your address.

Prerequisites for sending email in Rust

  • Rust 1.75 or later. Check with rustc --version.
  • A Mailcycle account on the Scale plan, or the free 7-day Scale trial. Sending with an API key starts at Scale. The trial needs no card. Sign up at app.mailcycle.email/operator/signup, then open Plans & Billing in the web app and choose Start free trial.
  • An API key. In the app, open API, then the Keys tab, name the key and choose Create key. The token starts with mak_ and is shown once, so copy it straight into your secret store. The quickstart walks through it.
  • An address to send from. Create one in the app, or with the crate as shown in step 2. New addresses are on Mailcycle’s shared domains, and on Scale you can bring your own domain.
  • For the Axum example: axum 0.8, tokio with the full feature, and serde with derive.

Step 1: Install the Mailcycle Rust email crate

The crate is mailcycle on crates.io, with API docs on docs.rs. Add it with Cargo:

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. If you only ever send, leave it off and the WebSocket dependency isn’t built at all; wait_for then checks the address every five seconds instead.

The crate is Apache-2.0 licensed and its encryption is checked against Mailcycle’s published test vectors. It’s synchronous, built on ureq, so a CLI, a cron job or a background worker can use it without pulling in an async runtime. Inside Tokio you hand calls to the blocking pool; step 4 shows how.

Step 2: Authenticate the Rust email API client with an API key

Never hard-code the key. Read it from the environment, and build the client once:

use mailcycle::{Mailcycle, Options};

fn client() -> Result<Mailcycle, Box<dyn std::error::Error>> {
    let api_key = std::env::var("MAILCYCLE_API_KEY")?;
    let phrase = std::env::var("MAILCYCLE_PHRASE").ok(); // optional: only needed to read mail

    let mc = Mailcycle::with_api_key(
        &api_key,
        phrase.as_deref(),
        Options { timeout_seconds: 15, ..Default::default() },
    )?;
    Ok(mc)
}

Mailcycle::with_api_key takes three things: the mak_… token, an optional recovery phrase, and Options. Options::default() points at the live API with a 30-second timeout; the example lowers the timeout to 15 seconds.

With the key alone, the client can send and manage addresses. Pass the phrase as well and it can also open mail and create addresses that receive it, because each address’s key is derived from the phrase locally and only the public half is uploaded. When both are given, the crate checks the phrase belongs to the key’s account before it opens anything. mc.can_decrypt() tells you which kind of client you have.

To create the address you’ll send from in code, use the phrase:

use mailcycle::{Mailcycle, NewAddress};

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

    let address = mc.addresses().create(NewAddress {
        prefix: Some("receipts".into()),
        label: Some("Order receipts".into()),
        ..Default::default()
    })?;
    println!("{} ({})", address.email_address, address.id);

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

prefix starts the address and the server adds a random ending. The label is sealed on your machine, so the server only ever stores ciphertext for it. Keep the printed email_address as MAILCYCLE_FROM and the id for later; the email addresses guide covers naming styles and retention.

Step 3: Send your first email from Rust

Outgoing::new(from, to, subject, text) builds a message with the four required fields, and mc.messages().send() sends it:

let sent = mc.messages().send(Outgoing::new(
    &from,                      // must be an address on this account
    "customer@example.com",     // one recipient per call
    "Your order has shipped",
    "Order 1042 left our warehouse this morning.",
))?;

println!("Message-ID: {}", sent.message_id);
println!("Sent copy:  {:?}", sent.sent_copy_id);

A few things worth knowing:

  • from must be one of your addresses. Anything else is refused with not_your_address. That’s the model: you send from addresses you own, and replies come back to them.
  • One recipient per call. To notify three people, call send three times. Each send counts against the plan’s daily sending limit.
  • send returns a SendResult. message_id is the Message-ID header the mail went out with. sent_copy_id is the id of the copy kept in the address’s Sent folder, which is stored encrypted like received mail.

Outgoing borrows its strings (Outgoing<'a> holds &'a str), so there’s no cloning to build one. Optional fields use struct update syntax over Outgoing::new, which is what the next sections do.

How to send HTML email in Rust

Set html and keep text as the plain-text version. Clients that don’t render HTML show the text part instead. from_name sets the display name on the From line:

use mailcycle::{Mailcycle, Outgoing};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mc = Mailcycle::with_api_key(&std::env::var("MAILCYCLE_API_KEY")?, None, Default::default())?;
    let from = std::env::var("MAILCYCLE_FROM")?;

    let name = "Ada";
    let link = "https://example.com/verify?token=abc123";
    let text = format!("Hi {name},\n\nConfirm your email address: {link}\n\nThe link expires in 30 minutes.");
    let html = format!(
        r#"<p>Hi {name},</p>
<p><a href="{link}" style="background:#111;color:#fff;padding:10px 16px;border-radius:6px;text-decoration:none">Confirm your email</a></p>
<p style="color:#666">The link expires in 30 minutes.</p>"#
    );

    mc.messages().send(Outgoing {
        html: Some(&html),
        from_name: Some("Acme Accounts"),
        ..Outgoing::new(&from, "ada@example.com", "Confirm your email address", &text)
    })?;
    Ok(())
}

Inline styles are the safe choice for email HTML, since many clients strip <style> blocks. If you render templates with a crate such as askama or minijinja, render both versions from the same data so they never drift apart. A sign-in or verification email like this one is exactly the kind of mail the API is built for.

The display name must be one line of up to 78 characters, without quotes, angle brackets or backslashes; the sending guide lists every field and its limits.

How to send email with an attachment in Rust

Attachments are raw bytes. The crate base64-encodes them for you, so you never touch the encoding:

use mailcycle::{Mailcycle, Outgoing, OutgoingAttachment};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mc = Mailcycle::with_api_key(&std::env::var("MAILCYCLE_API_KEY")?, None, Default::default())?;
    let from = std::env::var("MAILCYCLE_FROM")?;

    let pdf = std::fs::read("invoice-1042.pdf")?;
    let logo = std::fs::read("logo.png")?;

    let files = [
        OutgoingAttachment {
            mime_type: Some("application/pdf"),
            ..OutgoingAttachment::new("invoice-1042.pdf", &pdf)
        },
        OutgoingAttachment {
            mime_type: Some("image/png"),
            content_id: Some("logo"), // shown where the HTML says cid:logo
            ..OutgoingAttachment::new("logo.png", &logo)
        },
    ];

    mc.messages().send(Outgoing {
        html: Some(r#"<img src="cid:logo" alt="Acme" width="120"><p>Your invoice is attached.</p>"#),
        attachments: &files,
        ..Outgoing::new(&from, "billing@example.com", "Invoice 1042", "Your invoice is attached.")
    })?;
    Ok(())
}

OutgoingAttachment::new(filename, &bytes) borrows the bytes, so a large PDF isn’t copied. mime_type defaults to application/octet-stream; set it so the recipient’s client opens the file properly. A content_id turns a file into an inline image, which is how you embed a logo without loading anything remote.

A message can carry up to ten files, 3.5 MB between them, and the crate refuses anything over that before it makes a request. Program and script files such as .exe and .js are refused by the API with attachment_blocked.

How to send email from an Axum handler

Here’s where Rust’s ownership rules shape the code. The client is built once at start-up and shared through Axum state in an Arc. Because the crate’s calls block, each send runs on Tokio’s blocking thread pool with spawn_blocking, which keeps the async workers free to serve other requests.

use std::sync::Arc;

use axum::{extract::State, http::StatusCode, routing::post, Json, Router};
use mailcycle::{Error, Mailcycle, Outgoing};
use serde::Deserialize;

#[derive(Clone)]
struct AppState {
    mail: Arc<Mailcycle>,
    from: Arc<str>,
}

#[derive(Deserialize)]
struct Welcome {
    email: String,
    name: String,
}

async fn send_welcome(
    State(state): State<AppState>,
    Json(body): Json<Welcome>,
) -> Result<StatusCode, (StatusCode, String)> {
    let text = format!("Hi {},\n\nThanks for signing up. Reply to this email if you get stuck.", body.name);
    let html = format!("<p>Hi {},</p><p>Thanks for signing up. Reply to this email if you get stuck.</p>", body.name);

    // The crate uses blocking HTTP, so run the call on Tokio's blocking pool.
    let sent = tokio::task::spawn_blocking(move || {
        state.mail.messages().send(Outgoing {
            html: Some(&html),
            ..Outgoing::new(&state.from, &body.email, "Welcome to Acme", &text)
        })
    })
    .await
    .map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "send task failed".to_string()))?;

    match sent {
        Ok(_) => Ok(StatusCode::ACCEPTED),
        Err(Error::Api { code, .. }) if code == "invalid_address" => {
            Err((StatusCode::UNPROCESSABLE_ENTITY, "That email address doesn't look right.".into()))
        }
        Err(Error::Api { code, .. }) if code == "rate_limited" || code == "daily_send_limit" => {
            Err((StatusCode::SERVICE_UNAVAILABLE, "Try again shortly.".into()))
        }
        Err(err) => {
            eprintln!("welcome email failed: {err}");
            Err((StatusCode::BAD_GATEWAY, "Couldn't send the email.".into()))
        }
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mail = Mailcycle::with_api_key(&std::env::var("MAILCYCLE_API_KEY")?, None, Default::default())?;
    let state = AppState {
        mail: Arc::new(mail),
        from: std::env::var("MAILCYCLE_FROM")?.into(),
    };

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

Try it:

curl -X POST http://localhost:3000/welcome \
  -H "Content-Type: application/json" \
  -d '{"email":"ada@example.com","name":"Ada"}'

Why it’s shaped this way:

  • Mailcycle is Send + Sync, so an Arc<Mailcycle> can move into the blocking closure and one client serves every request. There’s no need for a Mutex.
  • The closure owns its data. move takes the cloned state, html, text and the request body, so the borrowed Outgoing lives entirely inside the closure and the borrow checker is happy.
  • from is an Arc<str>, so cloning the state per request is a reference-count bump, not a string copy.
  • Errors map to HTTP statuses by matching on the API’s error code. More on that below.

If you’d rather not block the request on the send at all, push the job onto a queue (a tokio::sync::mpsc channel feeding a worker, or your job system) and return 202 Accepted straight away. The worker then calls send in the same spawn_blocking pattern. The same approach works in Actix Web or Rocket: share one client and run calls off the async executor.

How to reply to an email in the same thread in Rust

Replies are where an inbox you own pays off. Set reply_to: Some(&message) and the crate sends the message’s id as inReplyTo and its Message-ID as inReplyToHeader, which threads your reply under the original in Gmail, Outlook and other clients:

mc.messages().send(Outgoing {
    reply_to: Some(&message),
    ..Outgoing::new(&address.email_address, &message.reply_to, &format!("Re: {}", message.subject), "Thanks, that's sorted.")
})?;

Note the to: message.reply_to is where an answer should go, the sender’s Reply-To if they set one and their From address otherwise. Send from the address the mail came to, so the conversation stays in one inbox.

How to receive email in Rust: wait for a reply and read it

Most send-only email APIs stop at delivery, and replies go to a mailbox you read some other way. With Mailcycle, the address you send from is also an inbox, and the same crate reads it. Reading needs the recovery phrase, because mail is stored sealed to keys derived from it and is opened in your process, not on the server.

This program sends a question, waits up to 15 minutes for the answer, and replies in the thread:

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

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

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mc = Mailcycle::with_api_key(
        &std::env::var("MAILCYCLE_API_KEY")?,
        Some(&std::env::var("MAILCYCLE_PHRASE")?),
        Default::default(),
    )?;
    let from = std::env::var("MAILCYCLE_FROM")?;
    let address = mc
        .addresses()
        .list()?
        .into_iter()
        .find(|a| a.email_address == from)
        .ok_or("MAILCYCLE_FROM is not an address on this account")?;

    // Take the time before sending, so a fast reply still counts.
    let since = SystemTime::now();
    mc.messages().send(Outgoing::new(
        &address.email_address,
        "ada@example.com",
        "Can we move Thursday's call?",
        "Would 3pm work instead of 11am?",
    ))?;

    let reply = mc.messages().wait_for(WaitFor {
        address_id: Some(&address.id),
        from: Some("ada@example.com"),
        since: Some(since),
        timeout: Duration::from_secs(15 * 60),
        ..Default::default()
    })?;
    println!("{} wrote: {}", reply.from_address, reply.text);

    // Answer in the same thread: reply_to fills in inReplyTo and the Message-ID header.
    mc.messages().send(Outgoing {
        reply_to: Some(&reply),
        ..Outgoing::new(&address.email_address, &reply.reply_to, &format!("Re: {}", reply.subject), "3pm it is. Thanks!")
    })?;
    Ok(())
}

wait_for listens on the event stream (with the events feature) and returns the first matching message, already opened. from and subject filter case-insensitively on substrings. Mail received from since on counts, even if it landed before the stream connected, which is why the time is taken before the send. If nothing matches in time you get Error::Api with code == "timeout", so ? propagates it with a clear reason. It blocks for as long as it waits, so in a server run it on a worker thread or in spawn_blocking, never directly on the async executor.

To read what’s already there, list a page of the inbox:

let page = mc.messages().list(&address_id, None, Some(20), None)?;
for message in &page.messages {
    if !message.opened {
        continue; // sealed to a key this phrase doesn't hold
    }
    println!("{} | {} | {}", message.received_at, message.from_address, message.subject);

    for attachment in message.attachments.iter().filter(|a| a.stored) {
        let bytes = mc.messages().attachment(message, attachment.index)?;
        std::fs::write(&attachment.filename, bytes)?;
    }
    mc.messages().mark_read(&message.id, true)?;
}

Each Message comes back parsed: text, html, subject, from_address, reply_to, message_id and an attachments list. mc.messages().attachment() fetches and decrypts a file locally and returns Vec<u8>. Pass page.next_cursor back to get the next page, or use mc.messages().all(&address_id, None) to walk every page.

Two details that matter when you show mail to people. A message that won’t open with your phrase comes back with opened: false and empty content rather than failing the whole page. And if you render HTML, use message.safe_html, which has every remote image and tracker stripped the way the Mailcycle apps do it; message.blocked lists what was removed. The reading mail guide covers folders, stars and paging.

Getting told about new mail with webhooks in Axum

For a service that should react to incoming mail without holding a wait open, add a webhook for message.received (on Operator and above) and verify each delivery before trusting it. Events carry ids, never content, so the handler fetches and opens the message itself:

use axum::{body::Bytes, http::{HeaderMap, StatusCode}};
use mailcycle::verify_webhook_signature_now;

async fn mailcycle_webhook(headers: HeaderMap, body: Bytes) -> StatusCode {
    let secret = std::env::var("MAILCYCLE_WEBHOOK_SECRET").unwrap_or_default();
    let signature = headers.get("Mailcycle-Signature").and_then(|v| v.to_str().ok());

    // Verify the raw bytes exactly as they arrived, before any parsing.
    if !verify_webhook_signature_now(&secret, &body, signature) {
        return StatusCode::UNAUTHORIZED;
    }

    let event: serde_json::Value = serde_json::from_slice(&body).unwrap_or_default();
    if event["type"] == "message.received" {
        let message_id = event["payload"]["messageId"].as_str().unwrap_or_default().to_owned();
        // Hand the id to a worker that calls mc.messages().get(&message_id).
        tokio::spawn(async move { println!("new mail: {message_id}") });
    }
    StatusCode::NO_CONTENT
}

Take the body as Bytes, not Json<…>: a body that has been parsed and re-serialised is a different string and won’t verify. For code that’s running anyway and has no public URL, mc.events().stream() delivers the same events over a WebSocket; see the event stream guide.

Rust email API error handling: match on the error code

Every call returns Result<T, mailcycle::Error>. API failures arrive as Error::Api { status, code, message }, where code is a stable, machine-readable string such as plan_required or rate_limited. Match on code, never on message. Requests that never got an answer come back with status: 0 and code: "network_error".

This example wraps any call in a small retry for the failures where retrying helps, then explains the rest:

use std::time::Duration;

use mailcycle::{Error, Mailcycle, Outgoing};

/// Runs `op`, retrying the failures that are worth another go.
fn with_retry<T>(mut op: impl FnMut() -> Result<T, Error>) -> Result<T, Error> {
    let mut wait = Duration::from_secs(2);
    let mut attempt = 1;
    loop {
        match op() {
            Err(Error::Api { status, code, .. })
                if attempt < 4 && (code == "rate_limited" || code == "network_error" || status >= 500) =>
            {
                eprintln!("attempt {attempt} failed with {code}; retrying in {wait:?}");
                std::thread::sleep(wait);
                wait *= 2;
                attempt += 1;
            }
            result => return result,
        }
    }
}

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

    let result = with_retry(|| {
        mc.messages().send(Outgoing::new(
            "alerts@yourdomain.com",
            "oncall@example.com",
            "Disk 91% full on db-2",
            "/var on db-2 is at 91%.",
        ))
    });

    match result {
        Ok(sent) => println!("sent {}", sent.message_id),
        Err(Error::Api { status, code, message }) => match code.as_str() {
            "plan_required" => eprintln!("sending with an API key needs Scale or above: {message}"),
            "not_your_address" => eprintln!("`from` must be an address on this account"),
            "invalid_address" => eprintln!("the recipient isn't a valid address"),
            "daily_send_limit" => eprintln!("today's sends are used up; they reset at 00:00 UTC"),
            "too_many_attachments" | "attachments_too_large" | "message_too_large" | "attachment_blocked" => {
                eprintln!("fix the attachments: {message}")
            }
            "address_paused" | "domain_not_sending" => eprintln!("this address can't send right now: {message}"),
            _ => eprintln!("send failed ({status} {code}): {message}"),
        },
        Err(other) => eprintln!("send failed: {other}"),
    }
    Ok(())
}

What the codes mean:

Code Status What to do
plan_required 403 Sending with an API key needs Scale or above. Start the trial or upgrade.
not_your_address 403 from isn’t an address on this account.
invalid_address 400 The recipient address is malformed. Show the user a validation error.
rate_limited 429 A per-minute limit. Back off and retry; the message says how long to wait.
daily_send_limit 429 The plan’s sends for today are used. Sending resumes at 00:00 UTC; don’t retry before then.
attachments_too_large, message_too_large 413 Trim or link the files instead.
domain_not_sending 409 An address on your own domain whose sending isn’t on yet. Check the domain again shortly.
5xx codes 500–503 A failure on our side or at a provider. Retry with backoff.

mailcycle::Error is #[non_exhaustive], so a match on it needs a catch-all arm; that’s what Err(other) is for. It also implements std::error::Error and Display, so it works with ?, Box<dyn Error>, anyhow and thiserror without adapters. The full list is in the errors reference, and the numbers behind rate_limited and daily_send_limit are on the rate limits page.

The raw send email API call: cURL equivalent

The crate is a thin, typed layer over one endpoint. Here is the same send as the TL;DR, in cURL:

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 order has shipped",
    "text": "Order 1042 left our warehouse this morning.",
    "html": "<p>Order 1042 left our warehouse this morning.</p>"
  }'
{ "sent": true, "messageId": "<…>", "sentCopyId": "msg_…" }

Attachments go in an attachments array of { filename, mimeType, content } objects with base64 content, and a reply adds inReplyTo and inReplyToHeader. The crate builds all of that from your structs, maps error bodies to Error::Api, refuses oversized attachments before the request, and never follows redirects, so your bearer token can’t be replayed to another host. Sending works the same from any language that can make an HTTPS request; the sending mail guide documents every field.

lettre and SMTP vs the Mailcycle crate

lettre is the established Rust crate for building and sending email over SMTP, and it’s a good one. Here’s a minimal lettre send for comparison:

use lettre::message::header::ContentType;
use lettre::transport::smtp::authentication::Credentials;
use lettre::{Message, SmtpTransport, Transport};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let email = Message::builder()
        .from("Acme <receipts@yourdomain.com>".parse()?)
        .to("customer@example.com".parse()?)
        .subject("Your order has shipped")
        .header(ContentType::TEXT_PLAIN)
        .body(String::from("Order 1042 left our warehouse this morning."))?;

    let mailer = SmtpTransport::relay("smtp.your-provider.com")? // TLS on port 465
        .credentials(Credentials::new(
            std::env::var("SMTP_USER")?,
            std::env::var("SMTP_PASSWORD")?,
        ))
        .build();

    mailer.send(&email)?;
    Ok(())
}

The code is just as short. The difference is what sits behind smtp.your-provider.com: you need an SMTP server or relay, credentials for it, the right port and TLS mode, an outbound network that allows SMTP, and a sending domain set up with that provider. And SMTP is send-only, so reading replies means a separate IMAP mailbox, the imap crate and a MIME parser.

lettre + SMTP Mailcycle crate
What you need An SMTP server or relay, username and password An API key (Scale plan or trial)
Transport SMTP on 25, 465 or 587, with STARTTLS or implicit TLS HTTPS to one API endpoint
Network Outbound SMTP ports open, which some hosts block Outbound HTTPS only
Sending domain Set up with your SMTP provider Shared domains ready to use, or your own domain on Scale
HTML, attachments, inline images Yes, with lettre’s MIME builder Yes, as struct fields; encoding done for you
Threaded replies Set In-Reply-To and References headers yourself reply_to: Some(&message)
Receiving replies Separate: IMAP mailbox, imap crate, MIME parser Same inbox: wait_for, list, webhooks, event stream
Stored mail Wherever your mailbox provider keeps it Encrypted with keys derived from your recovery phrase; opened on your machine
Async Sync and Tokio transports Blocking calls; use spawn_blocking in Tokio
Errors SMTP response codes and transport errors Stable API codes on Error::Api

Pick lettre if you already have an SMTP relay you’re happy with, or you need a native async transport. Pick the Mailcycle crate if you’d rather send over HTTPS from addresses you own and handle the replies in the same code, without a second system for receiving.

What to use the Rust email API for

The crate is built for mail that goes from your addresses to one person at a time: order and billing receipts, sign-in and verification emails, alerts to an on-call address, support replies, and messages your app or an AI agent sends and then waits to hear back on. Each call sends to one recipient, which suits mail that matters on its own.

That two-way shape is also why agents fit well. If you’re giving an AI agent its own inbox rather than code, Mailcycle’s MCP server does that without writing Rust at all; see give Claude Code its own email address and the AI agents guide.

Next steps for sending email in Rust

FAQ

How do I send an email in Rust?

Add the crate with cargo add mailcycle, build a client with Mailcycle::with_api_key, and call mc.messages().send(Outgoing::new(from, to, subject, text)). from must be an address on your Mailcycle account. The call returns a SendResult with the Message-ID, or a mailcycle::Error you can match on.

Can I send email from Rust without an SMTP server?

Yes. The mailcycle crate sends over HTTPS to the Mailcycle API, so there is no SMTP host, port, TLS mode or mailbox password to configure. You need an API key and an address on your account. Sending with an API key is on the Scale plan and above, or the free 7-day Scale trial.

How do I send HTML email in Rust?

Set the html field on Outgoing and keep a plain-text text body alongside it, for example Outgoing { html: Some(&html), ..Outgoing::new(from, to, subject, &text) }. Mail clients that can't show HTML fall back to the text.

How do I send an email with an attachment in Rust?

Read the file into bytes and pass it as an OutgoingAttachment in the attachments slice. The crate base64-encodes it for you. Set content_id on an image to show it inline where the HTML says cid: and that id.

Is the mailcycle crate async? Does it work with Tokio and Axum?

The crate is synchronous: its calls block, built on ureq, so it needs no async runtime. Inside Tokio or Axum, share one client in an Arc and run each call with tokio::task::spawn_blocking, so the request doesn't hold up the executor.

What is a good alternative to lettre for sending email in Rust?

If you'd rather not manage SMTP credentials, ports and TLS, an HTTP email API crate such as mailcycle sends with one call, and also lets you receive and read the replies in the same inbox.

How do I receive email in Rust?

With the mailcycle crate, mail sent to your addresses is stored encrypted, and mc.messages().list() or mc.messages().wait_for() returns it opened on your machine. Reading needs your recovery phrase alongside the API key. For push delivery, use webhooks or the event stream.

How do I reply to an email in the same thread from Rust?

Set reply_to: Some(&message) on Outgoing, where message is the email you're answering. The crate sends inReplyTo and the original's Message-ID header, so the reply lands in the same conversation in the recipient's mail client.

Can I send from my own domain?

Yes. On Scale you can add up to 10 of your own domains and create addresses on them, then send from those addresses with the same code. See Your own domains.

Send email from any language