For the complete site index, see llms.txt. Docs index: llms-docs.txt. Marketing corpus: llms-full.txt. Docs corpus: llms-full-docs.txt. Prefer markdown URLs where available (append .md).. Product skill: skill.md. Pricing: pricing.md. Docs MCP: /docs/mcp.

Tutorials/

How to Send Email in Rust: lettre, Axum and API

Pranav Patel

Pranav Patel

Co-founderยท13 min read

How to Send Email in Rust: lettre, Axum and API
Summary

Send email from Rust with lettre over SMTP or with an email API. Copy-paste examples for Axum and Actix Web, HTML email, attachments, background sending with tokio and retries without duplicates.

Rust has no email client in the standard library. Use the lettre crate to send over SMTP, or call an email API over HTTPS. For anything in production, send through a provider either way, from a domain you have verified.

This guide covers lettre with async tokio, the Reloop Rust SDK, Axum and Actix Web, then the production details: attachments, background sending and safe retries.

Working in another language? See how to send email in Python or how to send email in Node.js.


Which approach should you use?

lettre (SMTP)
Email API SDK
Install
cargo add lettre
cargo add reloop-email
Transport
SMTP on port 587 (STARTTLS)
HTTPS on port 443
Building the message
Message::builder(), MultiPart
A serde_json::json! value with html, text, attachments
Errors
smtp::Error with is_permanent() and is_transient()
Result with a boxed error
Safe retries
No, a retry can send twice
Yes, with an idempotency key
Async
Yes, with the tokio1 feature
Yes, async only

If you already have SMTP settings or need to work with a relay you do not control, use lettre. If you are writing the send call yourself, use the API.


Prerequisites

  1. A recent stable Rust toolchain (rustup update stable) and a tokio runtime
  2. A verified sending domain with SPF, DKIM and DMARC
  3. An API key from the Reloop dashboard. Keys start with rl_, and the same key works for the API and SMTP.
bash
export RELOOP_API_KEY=rl_your_api_key

Keep the key in the environment or a secrets manager, never in your code or git.


Method 1: Send email with lettre

lettre is the standard SMTP crate for Rust. It builds the MIME message, handles encoding and headers, and talks to the server. Enable the async tokio transport:

Cargo.toml
1[dependencies]
2lettre = { version = "0.11", features = ["tokio1", "tokio1-native-tls"] }
3tokio = { version = "1", features = ["full"] }

Then build a message with a plain-text and an HTML body, and send it:

rust
1use std::time::Duration;
2
3use lettre::message::MultiPart;
4use lettre::transport::smtp::authentication::Credentials;
5use lettre::{AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor};
6
7#[tokio::main]
8async fn main() -> Result<(), Box<dyn std::error::Error>> {
9 let email = Message::builder()
10 .from("Acme <hello@mail.acme.com>".parse()?)
11 .to("user@example.com".parse()?)
12 .subject("Welcome to Acme")
13 // Plain-text body first, then the HTML alternative
14 .multipart(MultiPart::alternative_plain_html(
15 String::from("Welcome! Thanks for signing up."),
16 String::from("<h1>Welcome!</h1><p>Thanks for signing up.</p>"),
17 ))?;
18
19 let creds = Credentials::new("reloop".to_owned(), std::env::var("RELOOP_API_KEY")?);
20
21 // starttls_relay connects on port 587 and requires STARTTLS
22 let mailer = AsyncSmtpTransport::<Tokio1Executor>::starttls_relay("smtp.reloop.sh")?
23 .credentials(creds)
24 .timeout(Some(Duration::from_secs(30)))
25 .build();
26
27 mailer.send(email).await?;
28 Ok(())
29}

The username can be any string. The password is your API key.

Build the transport once and reuse it. AsyncSmtpTransport keeps a connection pool and is cheap to clone. Not using async? lettre::SmtpTransport has the same builder and a blocking send(&email).

When port 587 is blocked

Some hosts block outbound 587. Reloop also accepts STARTTLS on port 2587 (and 2025), so only the port changes:

rust
1let mailer = AsyncSmtpTransport::<Tokio1Executor>::starttls_relay("smtp.reloop.sh")?
2 .port(2587)
3 .credentials(creds)
4 .timeout(Some(Duration::from_secs(30)))
5 .build();

Reloop does not offer implicit TLS on port 465, so do not use relay() with it: in lettre, relay() means implicit TLS on 465, and starttls_relay() means STARTTLS on 587. If the connection hangs or times out, see SMTP ports explained.

Handle SMTP errors

rust
1match mailer.send(email).await {
2 Ok(response) => println!("Accepted: {:?}", response.code()),
3 // 5xx reply: bad API key, rejected sender or recipient. Do not retry.
4 Err(e) if e.is_permanent() => eprintln!("Rejected: {e}"),
5 // 4xx reply: temporary. Safe to retry later.
6 Err(e) if e.is_transient() => eprintln!("Try again later: {e}"),
7 // Timeout, TLS or connection failure
8 Err(e) => eprintln!("Send failed: {e}"),
9}

A bad address fails earlier, when .parse() returns an AddressError. Parse user input before you queue anything.

Can I send with Gmail from Rust?

For a personal script, yes: use starttls_relay("smtp.gmail.com") with an App Password. For an app, no. Gmail limits personal accounts to about 500 recipients a day, every message comes from your @gmail.com address, and bulk sending gets the account suspended.


Method 2: Send email with the Rust SDK

Install

bash
cargo add reloop-email serde_json
cargo add tokio --features full

The crate is reloop-email and you import it as reloop_email.

Send an email

rust
1use reloop_email::ReloopClient;
2use serde_json::json;
3
4#[tokio::main]
5async fn main() -> Result<(), Box<dyn std::error::Error>> {
6 let reloop = ReloopClient::new(std::env::var("RELOOP_API_KEY")?, None);
7
8 let sent = reloop
9 .mail()
10 .send(json!({
11 "from": "Acme <hello@mail.acme.com>",
12 "to": "user@example.com",
13 "subject": "Welcome to Acme",
14 "html": "<h1>Welcome!</h1><p>Thanks for signing up.</p>",
15 "text": "Welcome! Thanks for signing up.",
16 }))
17 .await?;
18
19 println!("Sent: {} ({})", sent.id, sent.status);
20 Ok(())
21}

send takes a serde_json::Value, so the field names match the send email API one to one. It returns Result<SendMailResponse, Box<dyn std::error::Error>>. On success you get id, message_id and status. On a non-2xx response the error message contains the API's JSON error body (message, why, fix), but the status code is not exposed as a field.

rust
1match reloop.mail().send(params).await {
2 Ok(sent) => println!("Sent: {}", sent.id),
3 Err(e) => eprintln!("Send failed: {e}"),
4}

The error type is not Send. You cannot hold it across an .await inside tokio::spawn, or return it from a spawned task. Log it or turn it into a String right away.

Create the client once at startup and share it. It wraps a reqwest client with a connection pool. ReloopClient does not implement Clone, so put it in an Arc. The second argument to new is the base URL: pass None for Reloop Cloud, or Some("https://mail.acme.com".to_owned()) if you self-host Reloop.

Send to several recipients

rust
1reloop
2 .mail()
3 .send(json!({
4 "from": "Acme <hello@mail.acme.com>",
5 "to": ["ada@example.com", "grace@example.com"],
6 "cc": "team@acme.com",
7 "reply_to": "support@acme.com",
8 "subject": "Your weekly report",
9 "text": "Here is your report.",
10 "tags": [{ "name": "type", "value": "weekly_report" }],
11 }))
12 .await?;

Every address in to sees the others. For personalized mail, send one message per recipient.

Send a stored template

Keep copy out of your code so non-developers can edit it. Create the template in Reloop, then send it by ID with variables:

rust
1reloop
2 .mail()
3 .send(json!({
4 "from": "Acme <hello@mail.acme.com>",
5 "to": "user@example.com",
6 "subject": "Welcome to Acme",
7 "template": {
8 "id": "tmpl_welcome",
9 "variables": { "first_name": "Ada", "plan": "Pro" },
10 },
11 }))
12 .await?;

See templates for variables and defaults.


Axum

Put the client in your router state and extract it in handlers. Axum clones the state for every request, so wrap the client in an Arc:

rust
1use std::sync::Arc;
2
3use axum::{Json, Router, extract::State, http::StatusCode, routing::post};
4use reloop_email::ReloopClient;
5use serde::Deserialize;
6use serde_json::{Value, json};
7
8#[derive(Clone)]
9struct AppState {
10 reloop: Arc<ReloopClient>,
11}
12
13#[derive(Deserialize)]
14struct ContactForm {
15 email: String,
16 message: String,
17}
18
19#[tokio::main]
20async fn main() {
21 let api_key = std::env::var("RELOOP_API_KEY").expect("RELOOP_API_KEY is not set");
22 let state = AppState {
23 reloop: Arc::new(ReloopClient::new(api_key, None)),
24 };
25
26 let app = Router::new()
27 .route("/contact", post(contact))
28 .with_state(state);
29
30 let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
31 axum::serve(listener, app).await.unwrap();
32}
33
34async fn contact(
35 State(state): State<AppState>,
36 Json(form): Json<ContactForm>,
37) -> Result<Json<Value>, (StatusCode, &'static str)> {
38 let sent = state
39 .reloop
40 .mail()
41 .send(json!({
42 "from": "Acme Website <contact@mail.acme.com>",
43 "to": "support@acme.com",
44 "reply_to": &form.email,
45 "subject": format!("New message from {}", form.email),
46 "text": &form.message,
47 }))
48 .await
49 .map_err(|e| {
50 eprintln!("contact form send failed: {e}");
51 (StatusCode::BAD_GATEWAY, "Could not send message")
52 })?;
53
54 Ok(Json(json!({ "id": sent.id })))
55}

This uses Axum 0.8 (axum::serve with a TcpListener). The map_err turns the SDK error into a response before anything else is awaited, which keeps the handler future Send.

The visitor's address goes in reply_to, never in from. You can only send from your verified domain, and putting someone else's domain in from fails DMARC. Full example: Axum guide.


Actix Web

Actix Web runs on tokio, so the same client works. Share it with web::Data, which is already an Arc inside:

rust
1use actix_web::{App, HttpResponse, HttpServer, post, web};
2use reloop_email::ReloopClient;
3use serde::Deserialize;
4use serde_json::json;
5
6#[derive(Deserialize)]
7struct ContactForm {
8 email: String,
9 message: String,
10}
11
12#[post("/contact")]
13async fn contact(reloop: web::Data<ReloopClient>, form: web::Json<ContactForm>) -> HttpResponse {
14 let result = reloop
15 .mail()
16 .send(json!({
17 "from": "Acme Website <contact@mail.acme.com>",
18 "to": "support@acme.com",
19 "reply_to": &form.email,
20 "subject": format!("New message from {}", form.email),
21 "text": &form.message,
22 }))
23 .await;
24
25 match result {
26 Ok(sent) => HttpResponse::Ok().json(json!({ "id": sent.id })),
27 Err(e) => {
28 eprintln!("contact form send failed: {e}");
29 HttpResponse::BadGateway().body("Could not send message")
30 }
31 }
32}
33
34#[actix_web::main]
35async fn main() -> std::io::Result<()> {
36 let api_key = std::env::var("RELOOP_API_KEY").expect("RELOOP_API_KEY is not set");
37 // Create the client once, outside the factory closure
38 let reloop = web::Data::new(ReloopClient::new(api_key, None));
39
40 HttpServer::new(move || App::new().app_data(reloop.clone()).service(contact))
41 .bind(("0.0.0.0", 8080))?
42 .run()
43 .await
44}

The closure passed to HttpServer::new runs once per worker thread. Build the client outside it, or every worker gets its own client and connection pool.


Attachments

With the SDK, pass base64 content. Add the base64 crate for the encoding:

rust
1use base64::{Engine as _, engine::general_purpose::STANDARD};
2
3let pdf = tokio::fs::read("invoice-1042.pdf").await?;
4
5reloop
6 .mail()
7 .send(json!({
8 "from": "Acme Billing <billing@mail.acme.com>",
9 "to": "user@example.com",
10 "subject": "Your invoice #1042",
11 "text": "Your invoice is attached.",
12 "attachments": [{
13 "filename": "invoice-1042.pdf",
14 "content": STANDARD.encode(&pdf),
15 "content_type": "application/pdf",
16 }],
17 }))
18 .await?;

With lettre, wrap the body and the file in a mixed multipart:

rust
1use lettre::message::{Attachment, MultiPart, header::ContentType};
2
3let email = Message::builder()
4 .from("Acme Billing <billing@mail.acme.com>".parse()?)
5 .to("user@example.com".parse()?)
6 .subject("Your invoice #1042")
7 .multipart(
8 MultiPart::mixed()
9 .multipart(MultiPart::alternative_plain_html(
10 String::from("Your invoice is attached."),
11 String::from("<p>Your invoice is attached.</p>"),
12 ))
13 .singlepart(
14 Attachment::new(String::from("invoice-1042.pdf"))
15 .body(pdf, ContentType::parse("application/pdf")?),
16 ),
17 )?;

Keep attachments small. Many inboxes reject messages over 25 MB, and large files hurt deliverability. For big files, send a signed download link.


Retries without duplicate emails

A request times out and your code retries. If the first attempt actually went through, the user gets two emails. The API prevents this with an Idempotency-Key header: repeat a request with the same key and Reloop returns the original result instead of sending again.

The Rust SDK does not set this header, and its errors do not carry the HTTP status you need to decide whether to retry. For sends that retry, call the endpoint directly with reqwest:

toml
reqwest = { version = "0.13", features = ["json"] }
rust
1use std::time::Duration;
2
3use serde_json::Value;
4
5#[derive(Debug)]
6struct SendError {
7 status: u16, // 0 means the request never got a response
8 message: String,
9}
10
11impl SendError {
12 fn is_retryable(&self) -> bool {
13 self.status == 0 || self.status == 429 || self.status >= 500
14 }
15}
16
17async fn send_email(
18 http: &reqwest::Client,
19 api_key: &str,
20 idempotency_key: &str,
21 body: &Value,
22) -> Result<Value, SendError> {
23 let res = http
24 .post("https://reloop.sh/api/mail/v1/send")
25 .header("x-api-key", api_key)
26 .header("Idempotency-Key", idempotency_key)
27 // reqwest sends no User-Agent by default, and the API rejects requests without one
28 .header("User-Agent", "acme-app/1.0")
29 .json(body)
30 .timeout(Duration::from_secs(30))
31 .send()
32 .await
33 .map_err(|e| SendError { status: 0, message: e.to_string() })?;
34
35 let status = res.status();
36 if status.is_success() {
37 return res
38 .json()
39 .await
40 .map_err(|e| SendError { status: 0, message: e.to_string() });
41 }
42
43 Err(SendError {
44 status: status.as_u16(),
45 message: res.text().await.unwrap_or_default(),
46 })
47}

Base the key on the business event (receipt-{order_id}, welcome-{user_id}), not a new UUID per attempt, so a retry from any task or process is safe. Failed requests do not store the key, so you can fix the problem and retry with the same one.


Send in the background with a tokio task

Sending inside a request handler adds latency and fails the request when the provider is slow. A simple option is a channel and a worker task that owns the retries:

rust
1use tokio::sync::mpsc;
2
3struct WelcomeEmail {
4 user_id: String,
5 to: String,
6}
7
8fn spawn_email_worker(api_key: String) -> mpsc::Sender<WelcomeEmail> {
9 let (tx, mut rx) = mpsc::channel::<WelcomeEmail>(1_000);
10 let http = reqwest::Client::new();
11
12 tokio::spawn(async move {
13 while let Some(job) = rx.recv().await {
14 let body = serde_json::json!({
15 "from": "Acme <hello@mail.acme.com>",
16 "to": job.to,
17 "subject": "Welcome to Acme",
18 "text": "Thanks for signing up.",
19 });
20 // Same key on every attempt, based on the event
21 let key = format!("welcome-{}", job.user_id);
22 let mut delay = Duration::from_secs(1);
23
24 for attempt in 1..=5 {
25 match send_email(&http, &api_key, &key, &body).await {
26 Ok(_) => break,
27 Err(e) if e.is_retryable() && attempt < 5 => {
28 eprintln!("attempt {attempt} failed ({}), retrying", e.status);
29 tokio::time::sleep(delay).await;
30 delay *= 2;
31 }
32 Err(e) => {
33 // Other 4xx, or out of attempts: log it and move on
34 eprintln!("giving up on {key}: {} {}", e.status, e.message);
35 break;
36 }
37 }
38 }
39 }
40 });
41
42 tx
43}

Store the Sender in your Axum state and enqueue from the handler with try_send, which fails fast instead of waiting when the channel is full:

rust
1if let Err(e) = state.emails.try_send(WelcomeEmail { user_id, to: form.email }) {
2 eprintln!("email queue full or closed: {e}");
3}

Retry network errors (status 0), 429 and 5xx. Do not retry other 4xx errors: an invalid address or unverified domain fails the same way every time.

Be honest about what this queue is. The channel lives in memory, so a deploy, crash or OOM kill loses every job still in it. That is fine for a "someone commented" notification. For email that must arrive, such as receipts and password resets, write the job to your database in the same transaction as the change that caused it (an outbox table), and have the worker read from that table and mark rows as sent. The idempotency key makes it safe for the worker to pick up a row twice.


Testing without sending real email

  • Unit tests: put sending behind a small trait of your own (for example trait Mailer { async fn send(...) }) and use a fake that records messages in tests.
  • Staging: send to test addresses so you do not hurt your sender reputation with bounces.
  • Local SMTP: run Mailpit with docker run -p 1025:1025 -p 8025:8025 axllent/mailpit and point lettre at it without TLS or credentials. Open http://localhost:8025 to see the messages.
rust
1let mailer: AsyncSmtpTransport<Tokio1Executor> =
2 AsyncSmtpTransport::<Tokio1Executor>::builder_dangerous("localhost")
3 .port(1025)
4 .build();

builder_dangerous skips TLS, which is what Mailpit expects. Only use it for local testing.


Production checklist

  • API key in an environment variable or secrets manager
  • Sending domain verified with SPF, DKIM and DMARC
  • from on your verified domain; user addresses in reply_to
  • Both HTML and plain-text bodies
  • One shared client or transport, created at startup and held in state
  • Sending in a worker task, not the request handler
  • A durable queue or outbox table for email that must arrive
  • Retries only on network errors, 429 and 5xx
  • Idempotency keys on anything that retries
  • Webhooks for bounces and complaints
  • Disposable addresses blocked at signup (how)

FAQ

With lettre, give the message builder a multipart body that holds a plain-text part and an HTML part, as in the example above. With the Reloop SDK, put html and text keys in the json! value you pass to send.

relay connects with implicit TLS on port 465. starttls_relay connects on port 587 and upgrades the connection with STARTTLS. Reloop only offers STARTTLS, so use starttls_relay, and add .port(2587) if 587 is blocked.

The Reloop Rust SDK is async and needs a tokio runtime. In synchronous code, use lettre's blocking SmtpTransport, or build a tokio runtime and call block_on around the send.

The SDK returns a boxed std::error::Error that is not Send. If you keep it alive across an .await inside tokio::spawn or an Axum handler, the future is no longer Send. Convert the error to a String or log it before the next await.

Usually the sending domain is not authenticated, or the From domain does not match the domain that signed the message. Set up SPF, DKIM and DMARC, send from your own domain, and always include a plain-text body.


W: 320.0px180R20โˆ 45.0ยฐ

Ship your first email with Reloop
in minutes.

Open-source, deliverability-focused, and yours to self-host or run on Reloop Cloud. No lock-in, no rewrite later.

Reloop