← All posts

How to Send Email from Rust: SMTP with lettre or an HTTP API

Two working ways to send email from a Rust application: SMTP with the lettre crate, or an HTTP API with an SDK. Complete code, the errors to handle, and how to pick between them.

A Rust application has two practical ways to send email. It can speak SMTP to a mail server, usually with the lettre crate, or it can call an email provider's HTTP API. Both work. The difference is what you get back after sending, and how much you end up handling yourself.

Here is complete code for both that compiles, with EuroMail as the provider. The SMTP example works with any provider that offers authenticated SMTP; only the host and credentials change.

Option 1: SMTP with lettre#

lettre is the standard email crate for Rust. It builds the message, handles TLS, and talks to the server. For an async application on Tokio, add it like this:

[dependencies]
lettre = { version = "0.11", default-features = false, features = ["builder", "smtp-transport", "tokio1-rustls-tls", "pool", "hostname"] }
tokio = { version = "1", features = ["full"] }

Turning off the default features and picking tokio1-rustls-tls keeps OpenSSL out of your build, which makes cross-compiling and small container images easier.

use lettre::message::{header::ContentType, Mailbox};
use lettre::transport::smtp::authentication::Credentials;
use lettre::{AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor};

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

    let email = Message::builder()
        .from("Your Shop <[email protected]>".parse::<Mailbox>()?)
        .to("[email protected]".parse::<Mailbox>()?)
        .subject("Your order has shipped")
        .header(ContentType::TEXT_PLAIN)
        .body(String::from("Your order 1042 is on its way."))?;

    let mailer = AsyncSmtpTransport::<Tokio1Executor>::starttls_relay("smtp.euromail.dev")?
        .port(587)
        .credentials(Credentials::new("apikey".to_owned(), api_key))
        .build();

    let response = mailer.send(email).await?;
    println!("accepted: {}", response.code());
    Ok(())
}

Some things to know before you ship it:

  • Build the transport once. AsyncSmtpTransport keeps a connection pool, so create it at startup and share it, rather than building a new one for every email. Opening a fresh TLS connection per message is slow.
  • Port 587 with STARTTLS or 465 with TLS. Use starttls_relay for 587 and relay for 465. Never send credentials over an unencrypted connection; EuroMail refuses to authenticate until TLS is up.
  • The username is the literal word apikey and the password is your API key. Most providers that offer SMTP follow the same convention.
  • "Accepted" means the relay took it, not that it arrived. A 250 reply tells you the message is queued. Whether it reached the inbox, bounced, or was refused happens later, and SMTP has no way to tell your code.

SMTP fits when you already have it, when you want to stay provider-neutral, or when a framework or library expects an SMTP server.

Option 2: an HTTP API with an SDK#

With an API you send JSON over HTTPS and get structured errors and an ID back. The EuroMail Rust SDK wraps that:

[dependencies]
euromail = "0.7"
tokio = { version = "1", features = ["full"] }
use euromail::{EuroMail, EuroMailError, SendEmailParams};

#[tokio::main]
async fn main() -> Result<(), EuroMailError> {
    let api_key = std::env::var("EUROMAIL_API_KEY").expect("EUROMAIL_API_KEY is not set");
    let client = EuroMail::new(api_key);

    let params = SendEmailParams::new("[email protected]", "[email protected]")
        .subject("Your order has shipped")
        .text_body("Your order 1042 is on its way.")
        .html_body("<p>Your order <strong>1042</strong> is on its way.</p>")
        .idempotency_key("order-1042-shipped");

    match client.send_email(&params).await {
        Ok(sent) => println!("queued {} ({})", sent.id, sent.status),
        Err(EuroMailError::RateLimit { retry_after, .. }) => {
            eprintln!("rate limited, retry in {:?} s", retry_after);
        }
        Err(EuroMailError::Validation { code, message }) => {
            eprintln!("rejected: {code}: {message}");
        }
        Err(other) => return Err(other),
    }
    Ok(())
}

SMTP makes two of these things hard.

Errors you can match on. A rate limit and a bad request are different enum variants, and the rate limit tells you how long to wait. With SMTP you get a reply code and a line of text, and you have to work out from that whether to retry.

Safe retries. If your request times out, you do not know whether the email went out. Sending again might mean the customer gets it twice. The idempotency key solves this: send the same key again and you get the original result back instead of a second email. Use something tied to the event, like the order number and what happened to it.

Finding out what happened after sending#

Here the two options split. The API returns an ID, and you can ask what became of that message:

let detail = client.get_email(&email_id).await?;
for event in &detail.events {
    println!("{}", event.event_type); // e.g. "sent", "bounced"
}

You can also get the same events pushed to you with webhooks instead of asking. For order confirmations, password resets and anything else a customer is waiting for, knowing that a message bounced lets you show a warning or ask for a different address, rather than leaving them to wonder.

With SMTP you can still get this information, through the provider's dashboard or webhooks, but you have to connect the message you sent to the event yourself.

Which one to use#

Use the API for new code where you own the sending logic. You get typed errors, safe retries and a message ID to follow, with nothing extra to configure.

Use SMTP with lettre when you are adding email to something that already speaks SMTP, when you need to switch providers by changing a hostname, or when you build your own MIME messages.

Whichever you pick, delivery depends more on your domain than on your code. The From address has to be on a domain you have verified, with SPF and DKIM set up. Our guide to SPF, DKIM and DMARC explains what each record does. For the full list of settings, see the SMTP guide and the SDK documentation.

Share

Start sending GDPR-compliant email today

Create a free account and send your first email in minutes. Email storage and AI processing in Finland, with a DPA on every plan.

Create free account Read the Docs

Subscribe for tutorials and product updates. No spam.

Keep reading

Guide

Send Your First Email in 5 Minutes

A step-by-step guide to sending transactional email with euromail. Register, get an API key, add your domain, and send your first email using cURL, TypeScript, or Rust.