Enable the optional mail subsystem when your app needs password resets, signup confirmations, or transactional notifications:
autumn-web = { version = "0.11", features = ["mail"] }
Configuration
Development profile defaults to log transport. Production refuses log transport unless you explicitly acknowledge it.
[mail]
transport = "file" # log | file | smtp | disabled
from = "Acme <[email protected]>"
reply_to = "[email protected]"
file_dir = "target/mail"
[mail.smtp]
host = "smtp.example.com"
port = 587
username = "apikey"
password_env = "SMTP_PASSWORD"
tls = "starttls" # disabled | starttls | tls
Environment overrides use the same nested naming as the rest of Autumn:
AUTUMN_MAIL__TRANSPORT, AUTUMN_MAIL__FROM,
AUTUMN_MAIL__SMTP__HOST, AUTUMN_MAIL__SMTP__PASSWORD_ENV.
Sending
Mailer is a cloneable extractor backed by app state:
use autumn_web::prelude::*;
#[post("/password-reset")]
async fn reset(mailer: Mailer) -> AutumnResult<&'static str> {
let mail = Mail::builder()
.to("[email protected]")
.subject("Reset your password")
.html(html! { p { "Use this reset link." } })
.text("Use this reset link.")
.build()?;
mailer.send(mail).await?;
Ok("sent")
}
Attachments
Attach a file with .attach(filename, content_type, bytes) — call it once per
file, in the order you want them to appear:
use autumn_web::prelude::*;
#[post("/orders/{id}/confirm")]
async fn confirm(mailer: Mailer, id: String) -> AutumnResult<&'static str> {
let invoice: Vec<u8> = render_invoice_pdf(&id); // your own PDF generator
let mail = Mail::builder()
.to("[email protected]")
.subject("Your order confirmation")
.text("Thanks for your order! Your invoice is attached.")
.attach("invoice.pdf", "application/pdf", invoice)
.build()?;
mailer.deliver_later(mail);
Ok("queued")
}
- Attachments are declared-order,
multipart/mixedparts on both thesmtpandfiletransports, encodedbase64with theContent-Typeyou passed in. AMailwith zero attachments produces byte-for-byte the same message it always has — attachments are purely additive. - Filenames are sanitized against header injection and RFC 2231/2047-encoded automatically when they contain non-ASCII characters; you never need to escape a filename yourself.
Mail(including its attachments) isSerialize/Deserialize, so attachments survive a round-trip throughdeliver_laterand any custom [MailDeliveryQueue] outbox unchanged.- Out of scope for this API: inline/CID attachments (
cid:image embeds), attaching directly from a file path orBlobStorehandle, and attachment size limits — enforce those at the call site if your app needs them.
#[mailer]
Put templates on a small struct and let the macro generate send_* and
deliver_later_* helpers:
use autumn_web::prelude::*;
struct AccountMailer;
#[mailer]
impl AccountMailer {
fn reset_password(&self, to: String, token: String) -> Mail {
Mail::builder()
.to(to)
.subject("Reset your password")
.html(html! { p { "Token: " (token) } })
.text(format!("Token: {token}"))
.build()
.expect("static template should be valid")
}
}
Call AccountMailer.send_reset_password(&mailer, to, token).await for an
immediate send. Call deliver_later_reset_password when the request should not
wait on SMTP.
If the route also persists DB state (for example, writing an outbox row plus
creating a user), wrap the DB side in Db::tx so your write
sequence is atomic.
Auto-deferral inside db.tx
deliver_later (and the deliver_later_* methods generated by #[mailer])
automatically detect when they are called inside a db.tx block. Instead of
spawning the mail task immediately they register as an after-commit callback:
the mail task is spawned only after the transaction commits. If the transaction
rolls back, the mail is silently discarded — no ghost emails for data that was
never saved.
This deferral is not crash-safe delivery by itself. If the process exits after commit but before the callback runs, no mail handoff may happen. Use it to avoid mail for rolled-back writes; use an in-transaction outbox row plus a durable queue/worker when the mail itself must survive restarts.
use autumn_web::prelude::*;
use scoped_futures::ScopedFutureExt;
// Inside a db.tx block:
async fn register(mut db: Db, mailer: Mailer) -> AutumnResult<()> {
db.tx(|conn| async move {
// ... INSERT user ...
// Mail is only sent if the INSERT commits. Persist an outbox row too
// if the mail must survive process exit.
AccountMailer.deliver_later_welcome(&mailer, email, username);
Ok::<_, AutumnError>(())
}.scope_boxed())
.await
}
To bypass deferral and always spawn immediately — for example when outside a
transaction or when you deliberately want fire-and-forget semantics — use
deliver_later_eager / try_deliver_later_eager.
See Transactions -> after_commit for the full story on atomic DB + mail patterns.
Generator (autumn generate mailer)
autumn generate mailer <Name> scaffolds a mailer struct, templates, a dev
preview, and wires everything into src/main.rs in one step:
autumn generate mailer Welcome
Shared layout
By default the generator creates templates/mailers/_layout.html and
templates/mailers/_layout.txt on first use. Every subsequently generated
mailer template is a body fragment (no <head>, no <body>) composed into
the layout at build time via the {{ content }} slot:
<!-- templates/mailers/_layout.html (created once, never overwritten) -->
<!DOCTYPE html>
<html>
<body>
<!-- your branding, header, footer -->
{{ content }} <!-- per-mailer body goes here -->
</body>
</html>
Edit the layout freely after generation — subsequent generate mailer runs
skip it if it already exists, so your changes are preserved.
Generated mailers call .layout(...) to compose the body into the shared
shell at build time:
Mail::builder()
.to(to)
.subject("Welcome")
.html(include_str!("../../templates/mailers/welcome.html"))
.text(include_str!("../../templates/mailers/welcome.txt"))
.layout(
include_str!("../../templates/mailers/_layout.html"),
include_str!("../../templates/mailers/_layout.txt"),
)
.build()
.expect("valid mail")
Opting out of the shared layout
Pass --no-layout when a mailer needs a fully-custom HTML document (a
one-line plaintext alert, an email with a unique design, etc.):
autumn generate mailer Transactional --no-layout
With --no-layout the template is emitted as a self-contained full HTML
document and no .layout(...) call is generated.
List-Unsubscribe
autumn generate mailer Newsletter --list-unsubscribe newsletter
Adds a #[mailer(list_unsubscribe = "newsletter")] attribute and creates a
mail_unsubscribes suppression migration. See
Mail compliance: List-Unsubscribe.
Previewing Emails In Dev
When the active profile is dev and [mail] transport = "file", Autumn mounts
the mail preview UI at /_autumn/mail. The index shows recent .eml captures
from mail.file_dir newest-first and links to a detail view with sandboxed HTML,
plain text, an attachments list (filename and content type) when the message
has any, selected headers, and raw source.
Register sample-data previews with #[mailer_preview] and mail_previews![...]:
use autumn_web::prelude::*;
struct AccountMailer;
#[mailer]
impl AccountMailer {
fn reset_password(&self, to: String, token: String) -> Mail {
Mail::builder()
.to(to)
.subject("Reset your password")
.html(html! { p { "Token: " (token) } })
.text(format!("Token: {token}"))
.build()
.expect("static template should be valid")
}
}
#[mailer_preview]
impl AccountMailer {
fn reset_password_preview() -> Mail {
AccountMailer.reset_password("[email protected]".into(), "abc123".into())
}
}
autumn_web::app()
.mail_previews(mail_previews![AccountMailer])
.run()
.await;
Preview methods are zero-argument associated functions returning Mail; they
render through the UI without invoking any transport. Adding a new preview method
and refreshing /_autumn/mail is enough after the normal autumn dev recompile.
The preview UI is a dev-only surface. Setting [mail] preview = true outside the
dev profile fails startup with a mail.preview validation error instead of
silently exposing captured email in production.
Deferred Delivery (deliver_later)
Mailer::deliver_later and the generated deliver_later_* helpers do not
imply durable delivery on their own. The framework provides two paths:
-
In-process Tokio fallback (default). The mail send is spawned onto the current Tokio runtime. This is fine for local development and small single-process deployments, but it is not durable: a process restart, pod eviction, or deploy can drop the email after the request has already returned success.
-
The framework outbox. Set
outbox.enabled = true. If you set no queue,deliver_laterwrites the mail to theautumn_outboxtable, and the relay sends it. The mail survives a restart. To write it in your transaction, calloutbox.deliver_mail(conn, mail). See Transactional Outbox and Inbox. -
Durable backend via [
MailDeliveryQueue]. Implement the trait once for your queue of choice (DB outbox row, Redis stream, Harvest job, etc.) and register it via [AppBuilder::with_mail_delivery_queue] before.run():Rustuse autumn_web::prelude::*; struct OutboxQueue { /* db handle */ } impl MailDeliveryQueue for OutboxQueue { fn enqueue<'a>( &'a self, mail: Mail, ) -> std::pin::Pin<Box<dyn std::future::Future< Output = Result<(), MailError>, > + Send + 'a>> { Box::pin(async move { // INSERT into mail_outbox (...) VALUES (...) // Return Ok(()) once the row is durably committed. Ok(()) }) } } autumn_web::app() .with_mail_delivery_queue(OutboxQueue { /* ... */ }) .run() .await;When the queue needs framework-managed resources (the DB pool, channels, etc.) that only exist after the [
AppState] is built, use [AppBuilder::with_mail_delivery_queue_factory] instead. The factory runs once with the liveAppStateimmediately beforeinstall_mailer:Rustautumn_web::app() .with_mail_delivery_queue_factory(|state| { let pool = state.pool().expect("DB pool required").clone(); Ok(OutboxQueue::new(pool)) }) .run() .await;When a queue is registered,
deliver_laterroutes through it instead of the in-process fallback.Mail— attachments included — is the same value acrosssend,deliver_later, and the queue, so a deferred email with attachments arrives intact.
Production Guard
In prod/production, with an active mail transport and no durable backend
registered, Autumn does not fail to start — apps that never call
deliver_later/deliver_later_eager (e.g. only mailer.send(...)) are
unaffected either way. Startup logs a warning, and the guard is enforced lazily
at the call site instead: try_deliver_later/try_deliver_later_eager return
MailError::NoDurableQueueInProduction on the first deferred send, until you
either register a MailDeliveryQueueHandle or explicitly opt in. The plain
deliver_later/deliver_later_eager convenience methods call these
fallible try_* variants but only log the error — they still return (), so
a caller using them cannot observe or match on the typed error and should not
assume the mail was scheduled just because the call returned.
[mail]
transport = "smtp"
allow_in_process_deliver_later_in_production = true
The flag is intended as an acknowledged single-replica escape hatch, not a
recommended production setup — with it set, deliver_later falls back to an
in-process Tokio task instead of failing, but delivery is not durable across
restarts or replicas.
DB-Write + Mail Patterns (Outbox)
When a request both writes to the DB and dispatches mail, persist the mail intent in the same transaction as the domain write, then make the dispatch idempotent so retries recover:
- Inside
Db::tx, insert the user row and anemail_outboxrow ((id, kind, payload, status='pending')) atomically. - After commit, call
mailer.deliver_later(...)as an optional wake-up hint, or let a worker poll pending outbox rows. - A
MailDeliveryQueueimplementation reads the outbox row, sends the email, and marks the rowsent. On retry, it skips already-sentrows. This is the canonical outbox pattern: the DB transaction is the source of truth for "the user signed up", and the queue worker is responsible for at-least-once delivery without losing mail across restarts.
For the transaction shape see Db::tx.
Transports
log: writes headers and full bodies to tracing at INFO. Default fordev.file: writes.emlfiles undertarget/mailby default. This is ideal for integration tests and local inspection.smtp: sends through Lettre with rustls and Tokio.disabled: accepts sends and drops them.
For provider APIs like SES, Postmark, or SendGrid, implement MailTransport and
build a Mailer::with_transport(...).
Receiving Mail (Inbound Email)
Everything above sends. Autumn also receives: support inboxes, reply-by-email
threading, ticket routing, and bounce processing all arrive as an HTTP webhook
from your mail provider, which Autumn verifies, parses into an
InboundEmail, and dispatches to a handler you write.
Receiving is its own Cargo feature, and it does not come with mail:
autumn-web = { version = "0.11", features = ["mail", "inbound-mailgun"] }
inbound-mail is the base feature — it carries the router, the RFC 5322 parser,
and the generic and Mailgun adapters. inbound-mailgun and inbound-ses both
imply it and name the provider you are wiring up. The two are not
interchangeable: inbound-mailgun compiles no extra code today and is there to
state intent, while inbound-ses is what actually pulls in the SNS signature
verifier, without which an SES endpoint cannot work at all.
Inbound email webhooks: Mailgun, SES, and generic
Each InboundMailEndpointConfig you register becomes one POST route with a
50 MB body limit. What that route checks before parsing depends on which
constructor built it:
| Constructor | Provider | What it checks before parsing |
|---|---|---|
InboundMailEndpointConfig::mailgun(path, signing_key) | Mailgun | HMAC-SHA256 over timestamp || token, compared in constant time, with the timestamp required to be within 5 minutes of now |
InboundMailEndpointConfig::ses(path) | AWS SES via SNS | SNS RSA signature against the certificate named by SigningCertURL, plus the TopicArn binding below |
InboundMailEndpointConfig::generic(path) | Postfix, a relay, anything posting raw RFC 5322 | X-Inbound-Signature: HMAC-SHA256(key, body) — only if you set a key. With none set it checks nothing |
Mailgun and SES authenticate unconditionally, and both fail closed: a Mailgun
endpoint whose signing key is empty answers 500 to every request rather than
accept unsigned mail, a bad signature or a timestamp outside the window is
401, and the SES cases are below.
Nothing here de-duplicates. Mailgun's timestamp check is a freshness bound,
not replay protection: it caps how long a captured request stays usable at five
minutes, and within that window the same timestamp/token/signature triple
is accepted every time it arrives, because no delivery identifier is retained.
Providers redeliver on their own schedule too, so a handler sees the same
message more than once for reasons that have nothing to do with an attacker.
So make any handler with side effects idempotent, keyed on something that
identifies the message rather than the conversation.
email.headers.get("message-id") is the usual choice — and note email.headers
is keyed by lower-cased name on both the Mailgun and RFC 5322 paths, so
get("Message-Id") returns None. Do not key on the plus-address token: in
the reply scheme below it identifies the thread, so every reply in that thread
carries the same value and you would drop all but the first. Message-Id comes
from the sender, so scope the key to its endpoint and expire it rather than
trusting it as a globally unique id.
This is the one place inbound mail differs from
autumn generate webhook, whose
SignedWebhook extractor does keep replay markers.
The generic endpoint is unauthenticated by default.
generic(path)leaves bothsigning_keyandsigning_key_envunset, and with no key the signature check is skipped entirely — every body that arrives is parsed and dispatched to your handlers. That is fine for a Postfix relay reachable only on a private network, and it is a forged-mail hole on anything an attacker can POST to. Set a key before the route is internet-facing.
Set one with signing_key_env, which is read at startup so the secret stays out
of the source. This applies to Mailgun and generic endpoints only — an SES
endpoint is authenticated by the SNS certificate signature and its topic ARN,
and build_routes never hands its signing key to the route, so setting one
there does nothing:
use autumn_web::inbound_mail::{InboundMailEndpointConfig, InboundMailProvider};
let endpoint = InboundMailEndpointConfig {
path: "/inbound/mailgun".to_string(),
provider: InboundMailProvider::Mailgun,
signing_key_env: Some("MAILGUN_SIGNING_KEY".to_string()),
..Default::default()
};
resolve_signing_key() prefers the literal signing_key when both are set. If
the variable is missing at startup the key resolves to nothing, and the endpoint
rejects rather than skips verification — a missing secret is a 500, never an
open door.
SES endpoints need a topic ARN
An SES endpoint without .with_topic_arn(...) rejects every notification
with 503, and logs an error naming the path at startup. This is not a
hardening step you can postpone: without the ARN, any AWS account could
subscribe your endpoint to a topic of their own and deliver validly-signed
payloads, so the endpoint fails closed instead.
use autumn_web::inbound_mail::InboundMailEndpointConfig;
let endpoint = InboundMailEndpointConfig::ses("/inbound/ses")
.with_topic_arn("arn:aws:sns:us-east-1:123456789012:inbound-mail");
A notification carrying any other TopicArn is rejected with 401. SNS
subscription confirmation is handled for you — Autumn fetches the SubscribeURL
and answers 500 if that fetch fails, so SNS retries.
Autumn fetches only from SNS. Both URLs must be
https://sns.<region>.amazonaws.com/… (.amazonaws.com.cn for a cn-
region), with no user info and no port. The aws, aws-cn and aws-us-gov
partitions are supported. Other partitions get 401.
SigningCertURLmust name one.pemfile. Any other URL gets401.- The certificate fetch does not follow redirects. A redirect, a transport
error, or a body with no
Content-Lengthor more than 16 KiB gets502. An error status gets503, so SNS tries again. SubscribeURLmust be/?Action=ConfirmSubscriptionwith yourTopicArn. Any other URL gets400and Autumn does not fetch it.
The SES adapter also needs the inbound-ses feature specifically: with only
inbound-mail enabled the SNS signature verifier is not compiled in, and rather
than accept unauthenticated notifications the endpoint answers 503 to all of
them and says so in an error log.
Routing a message to a handler
Write a handler, annotate it, and register the companion it generates:
use autumn_web::prelude::*;
// `#[inbound_mail]` is NOT in the prelude, unlike `#[mailer]` and
// `#[mailer_preview]`. Import the attribute itself:
use autumn_web::inbound_mail;
use autumn_web::inbound_mail::{InboundEmail, InboundMailEndpointConfig, InboundMailRouter};
#[inbound_mail(to = "[email protected]")]
async fn support(email: InboundEmail) -> AutumnResult<()> {
tracing::info!(from = %email.from, subject = %email.subject, "support mail");
Ok(())
}
autumn_web::app()
.inbound_mail_router(
InboundMailRouter::new()
.endpoint(InboundMailEndpointConfig::mailgun("/inbound/mailgun", key))
.handler(support_handler_info()),
)
.routes(routes![...])
.run()
.await;
#[inbound_mail] generates the support_handler_info() function from the
handler's name; Macro Transparency shows exactly what it
expands to.
The to argument becomes a RecipientPattern, and the spelling picks the kind:
to = … | Pattern | Matches |
|---|---|---|
"[email protected]" | Exact | that address, case-insensitively |
"ticket*" | LocalPrefix | any local part starting ticket — ticket@, ticket+42@, tickets@. The * is stripped along with a trailing ., so "ticket.*" is the same rule; "ticket+*" keeps the + in the prefix and therefore does not match a plain ticket@ |
"replies+{token}@app.example" | PlusAddress | the token is captured; drop @domain to match any domain |
"*" or omitted | Any | every message, even one delivered Bcc-only with no To |
Handlers are tried in registration order and the first match wins, so register the specific patterns before the catch-all.
A message that matches nothing is logged at WARN and dropped — the webhook
still answers 200, so the provider never retries it. Register
.fallback(handler) if you would rather see those messages than lose them.
Reply-by-email and plus-address routing
PlusAddress is how a reply gets back to the thread it belongs to. Address the
outgoing mail's Reply-To as replies+<thread-id>@your.app, and the token comes
back on the way in:
use autumn_web::prelude::*;
use autumn_web::inbound_mail;
use autumn_web::inbound_mail::InboundEmail;
#[inbound_mail(to = "replies+{token}@app.example")]
async fn reply(email: InboundEmail) -> AutumnResult<()> {
let thread_id = email.plus_token().unwrap_or_default();
tracing::info!(thread_id, "reply received");
Ok(())
}
The token keeps its original casing even though address matching is case-insensitive.
Sync or background: when the webhook returns 200
processing = "background" is the default, and it decides what the provider
sees:
"background"answers200immediately and runs the handler in a spawned task. A handler that then returnsErris logged atERRORand the message is gone — the provider already got its200and will not retry."sync"awaits the handler first.Errbecomes a500, so whether the message gets another chance is down to your provider's retry policy rather than being decided for you. Handlers that must not silently lose a message belong here.
Choose "sync" for anything you would be sorry to drop, and keep it fast enough
for the provider's webhook timeout.
Bounces and spam verdicts
Two handlers run ahead of recipient matching:
.on_bounce(handler)fires when the provider's own webhook field reports a bounce (Mailgun'sX-Mailgun-Bounced-Address). It is never inferred from headers inside the forwarded message, so a sender cannot spoof their way into the bounce path.email.bounced_addresscarries the address that failed, which is notemail.to— on a bounce that is your own inbound address..on_spam(handler)fires on a provider spam verdict (X-Mailgun-Sflag: Yes), readable in full viaemail.spam_report. This is the provider's inbound verdict, not a recipient's complaint.
To turn a bounce into a suppression entry, wire
autumn_web::mail::suppression::record_inbound into .on_bounce — it reads
bounced_address and never falls back to email.to. Routing .on_spam there
too is a deliberate no-op: an inbound spam verdict names no complainant, so
there is no address it could safely suppress.
Scaffolding a handler
autumn generate inbound-mail Support writes the handler, its module wiring, a
smoke test and the InboundMailRouter registration in src/main.rs — see
Generators.
It scaffolds a Mailgun endpoint and nothing else: there is no provider flag,
so the emitted .endpoint(...) is always
InboundMailEndpointConfig::mailgun("/inbound/mailgun", …) and the generated
test posts a Mailgun fixture. For SES or generic, generate it anyway and swap
that one call for ::ses(path).with_topic_arn(…) or ::generic(path) — the
handler, the routing and the wiring are provider-independent.
Swapping the call is the whole job for ::generic: the inbound-mailgun feature
the generator adds implies inbound-mail, which carries the generic adapter.
SES needs inbound-ses in that feature list too — added alongside
inbound-mailgun or in place of it. Without it the SNS verifier is not compiled
in and the endpoint answers 503 to every request, as
SES endpoints need a topic ARN describes. The
generated integration test posts a Mailgun fixture, so it needs rewriting for
either other provider.
Production Checklist
- Enable the
mailfeature. - Use
transport = "smtp"inprod. - Keep SMTP secrets in environment variables via
password_env. - Add a plain-text fallback for every HTML email.
- Assert file-transport
.emlcontents in integration tests. - Register a
MailDeliveryQueueHandle(Harvest, DB outbox, Redis, etc.) for durabledeliver_laterretries. Without one,try_deliver_later/try_deliver_later_eagerreturnMailError::NoDurableQueueInProductioninprodunlessmail.allow_in_process_deliver_later_in_production = trueis set, in which case Autumn falls back to an in-process Tokio task. The plaindeliver_later/deliver_later_eagermethods only log that error — they don't propagate it to the caller. Apps that only usemailer.send(...)are unaffected and need neither. - For DB-write + mail-orchestration flows, use the Transactions Guide for the canonical atomic write pattern.
- Shipping newsletters, digests, or other bulk mail? See Mail compliance: List-Unsubscribe to meet Gmail/Yahoo bulk-sender requirements with one attribute and one config key.
- Receiving mail? Set a signing key on every Mailgun and generic endpoint — a
genericone with no key authenticates nothing, and an unresolved key is a500rather than an open route. Give every SES endpoint a topic ARN instead; it takes no signing key. Make side-effecting handlers idempotent — no inbound endpoint de-duplicates — and decide per handler whetherbackgroundlosing a message on error is acceptable. See Receiving Mail.