Frameworks

How to send email in Rust

Short answer

To send email in Rust, either make an HTTPS request to an email API with reqwest and serde_json, or build a message with the lettre crate and send it over SMTP. The API route is one request per email and fits async services well; lettre is the standard choice when you need SMTP. Either way, verify your sending domain with SPF, DKIM and DMARC first.

Last checked 16 November 2026

You can send email from Rust in two ways: make an HTTPS request to an email API with reqwest, or build a message with the lettre crate and send it over SMTP. Both are production ready. For app email such as sign-up confirmations, login codes and receipts, the API is less code and fits async services well. Use lettre when you need SMTP, for example to talk to an internal relay.

Option 1: reqwest and an email API

An email API takes a JSON body and answers with an id. The examples below use Mailcandor; most email APIs have the same shape.

Add the dependencies to Cargo.toml. reqwest needs its json feature for the .json() helper:

[dependencies]
reqwest = { version = "0.13", features = ["json"] }
serde_json = "1"
tokio = { version = "1", features = ["full"] }

Then send:

use serde_json::{json, Value};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let key = std::env::var("MAILCANDOR_KEY")?;

    let res = reqwest::Client::new()
        .post("https://api.mailcandor.com/v1/emails")
        .bearer_auth(key)
        .header("Idempotency-Key", "signup-4821-welcome")
        .json(&json!({
            "from": "Acme <hello@acme.com>",
            "to": "sam@example.com",
            "subject": "Your login code",
            "html": "<p>Your code is <b>481 203</b></p>",
            "text": "Your code is 481 203"
        }))
        .send()
        .await?;

    let status = res.status();
    let body: Value = res.json().await?;

    if !status.is_success() {
        let err = &body["error"];
        return Err(format!(
            "{}: {}",
            err["type"].as_str().unwrap_or("error"),
            err["message"].as_str().unwrap_or("")
        )
        .into());
    }

    println!("queued {}", body["id"].as_str().unwrap_or_default());
    Ok(())
}

A few details matter here:

  • Reuse the client. reqwest::Client holds a connection pool. Create it once (for example in your app state) and clone it where you need it; clones share the pool.
  • The Idempotency-Key header makes retries safe. If a timeout makes you send the same request twice, the second call returns the first response instead of sending a second email. Use a value unique to the email, such as the order or user id plus the email type.
  • Status 202 means accepted, not delivered. The API queues the email and returns {"id": "...", "status": "queued"}. Delivery, bounces and spam complaints arrive later as webhooks.

If you prefer typed bodies, derive serde::Serialize on a struct and pass it to .json() instead of the json! macro.

Sending many emails at once

For a batch of notifications, POST /v1/emails/batch takes a JSON array of up to 100 emails in one request. Batches cannot include attachments or a scheduled time, so send those one by one.

Option 2: lettre over SMTP

lettre is the standard Rust mail crate. Its default features include the message builder, the SMTP transport, connection pooling and TLS. The current release line is 0.11 and it needs Rust 1.85 or newer.

[dependencies]
lettre = "0.11"
use lettre::message::{header::ContentType, Mailbox};
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 <hello@acme.com>".parse::<Mailbox>()?)
        .to("sam@example.com".parse::<Mailbox>()?)
        .subject("Your login code")
        .header(ContentType::TEXT_HTML)
        .body(String::from("<p>Your code is <b>481 203</b></p>"))?;

    let creds = Credentials::new(
        "mailcandor".to_owned(),
        std::env::var("MAILCANDOR_KEY")?,
    );

    // relay() uses implicit TLS on port 465
    let mailer = SmtpTransport::relay("smtp.mailcandor.com")?
        .credentials(creds)
        .build();

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

SmtpTransport::relay connects on port 465 with TLS from the first byte. If your network only allows port 587, use SmtpTransport::starttls_relay, which upgrades the connection with STARTTLS. Our SMTP ports guide explains the difference.

To send both HTML and plain text, replace .header(...).body(...) with .multipart(MultiPart::alternative_plain_html(text, html)) from lettre::message::MultiPart. Mail clients show the HTML part and fall back to text.

Async lettre with Tokio

Inside an async web server, do not call the blocking transport on the async runtime. Either use tokio::task::spawn_blocking, or enable the async transport:

lettre = { version = "0.11", features = ["tokio1", "tokio1-native-tls"] }

Then build an AsyncSmtpTransport::<Tokio1Executor> with the same relay and credentials calls and .send(email).await. Build the transport once and share it, since it keeps a pool of SMTP connections.

Which should you choose?

reqwest + email API lettre + SMTP
Crates reqwest, serde_json lettre
Per email One HTTPS request SMTP conversation (pooled)
Async Native Needs the tokio1 features
Delivery events Webhooks keyed by email id Not part of SMTP
Retry safety Idempotency-Key header Your own de-duplication
Best for Web services, workers, serverless Existing SMTP relays, internal mail

Our SMTP vs API guide covers the trade-offs in more depth.

Handling errors and rate limits

Treat email as a side effect that can fail without breaking the request that caused it:

  • Send from a background task. Push the email onto a queue or a tokio::spawned task so a slow provider does not slow your HTTP handler.
  • Retry on 429 and 5xx only. A 4xx error such as a bad from address will fail again. The error body names the problem: {"error": {"type", "message", "field"}}.
  • Read the rate limit headers. Mailcandor returns ratelimit-* headers on every response. Limits are per team, from 5 requests a second on the free Starter plan to 50 on Team, so back off when you get close.

Before you send: verify your domain

Whichever crate you use, mail from a domain without SPF, DKIM and DMARC is likely to land in spam. Add your domain in your provider’s dashboard and publish the DNS records it gives you. The SPF, DKIM and DMARC setup guide walks through each record.

Sending with Mailcandor

Mailcandor gives you both routes with one key: the REST API at https://api.mailcandor.com/v1 and an SMTP relay at smtp.mailcandor.com (username mailcandor, password your API key). There is no Rust SDK to install; reqwest or lettre is all you need. The free Starter plan includes 3,000 emails a month, and access is currently by request on the pricing page.

Questions

What is the best crate for sending email in Rust?

lettre is the most widely used crate for building and sending email over SMTP. If you send through an email API, you only need an HTTP client such as reqwest and serde_json for the body.

Does lettre support async?

Yes. AsyncSmtpTransport works with Tokio or async-std when you enable the matching features, such as tokio1 and tokio1-native-tls. The blocking SmtpTransport is fine for scripts and simple workers.

Which port should lettre use?

SmtpTransport::relay connects with implicit TLS on port 465. SmtpTransport::starttls_relay uses port 587 and upgrades the connection with STARTTLS. Both are encrypted.

Can I send email from Rust without an SMTP server?

Yes. An email API accepts a JSON request over HTTPS, so any HTTP client works and you never open an SMTP connection yourself.

Related

Send with someone on your side.

Unlimited domains on every plan, a person before any block, and 3,000 emails a month free. Tell us what you send and we set you up within one business day.