Most applications send mail: a confirmation after a booking, a sign-in
code, a password reset. The mail plugin sends a message through a
transport (the console, SMTP, Mailgun…), renders it from templates, and
records what became of it: delivered, opened, failed.
Coming from Django: this is
django.core.mail(send_mail,EmailMessage,EMAIL_BACKEND) and, for the delivery events, whatdjango-anymailadds. Django’s console, file-based and in-memory backends are here too, as theConsole,FileandMemorytransports.
Setting it up
Turn on the Cargo feature. mail gives the development transports;
mail-smtp adds SMTP, and mail-mailgun adds Mailgun:
# Cargo.toml of the application
rind = { version = "…", features = ["mail-smtp"] }
Then give the plugin to the application, in app():
#![allow(unused)]
fn main() {
// sample/src/lib.rs
pub fn app() -> rind::Application {
bare_app()
// …
.with(
rind::mail::Mailer::from_env()
.expect("RIND_MAIL_URL")
.from("The railway <noreply@railway.example>")
.templates_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/mail"))
.expect("the mail templates"),
)
}
}
Mailer::from_env() reads three environment variables:
| Variable | What it says |
|---|---|
RIND_MAIL_URL | the transport: console: (the default), smtp://…, mailgun://…… See Choosing a transport |
RIND_MAIL_FROM | the default sender, when the code does not give one with .from(..) |
RIND_MAIL_REDIRECT | an address that receives every message instead of its real recipients: see Sending everything to yourself |
With nothing set, every message is written to the log. This is what you want while you develop: you can read the sign-in codes in the terminal.
Sending a message
A request handler (here, a resource’s saved hook) finds the mailer
among the application’s services, builds a message from a template, and
sends it:
#![allow(unused)]
fn main() {
// sample/crates/booking/booking-api/src/reservations/views.rs
let Some(mailer) = ctx.service::<rind::mail::Mailer>() else {
return Ok(());
};
let message = mailer
.message(
"reservation_confirmed",
serde_json::json!({ "code": code, "journey": journey, "username": username }),
)?
.to(&email)
.tag("reservation")
.reference(&format!("reservation:{id}"));
mailer.send(&ctx.db, message).await?;
}
mailer.message(name, context) renders the template name with the
values of context, and gives a Message with its subject, its text
and its HTML. You then add the recipients and the rest.
send waits until the transport has taken the message. It takes a Db
because it records the message in the table rind_mail (see
What became of a message).
What a message holds
A Message is built with methods that each add one thing:
.from(..): the sender,"Name <address>"or a bare address. When a message has none, the mailer’s sender is used..to(..),.cc(..),.bcc(..): one recipient per call; call them again for more..reply_to(..),.subject(..),.text(..),.html(..)..attach(name, content_type, bytes): a file joined to the message..header(name, value): a header of your own, such asList-Unsubscribe..tag(..): a tag for the transport’s statistics (Mailgun groups its numbers by tag)..track(true): ask for open and click tracking, when the transport does it..reference(..): your application’s own key for the message, such asreservation:42. Every event about the message gives it back, so you can find which reservation a bounce is about.
You can also build a message without a template:
Message::new().to("bob@example.org").subject("Hello").text("…").
When sending fails
A message without any recipient, or without a sender (neither its own
nor the mailer’s), is refused before it reaches the transport. The
transports that build a MIME message (File, Smtp) also refuse an
address they cannot read. Console and Memory do not check the
addresses, and Mailgun checks them itself.
The error, a MailError, says what to do next:
MailError::Temporary: the transport may take it later. Try again.MailError::Permanent: the transport will not take it.MailError::Invalid: the message itself is wrong (no recipient, a bad address, a template that does not render).
Returned from a handler with ?, a MailError becomes a 500 answer.
Templates
A template is two or three files in the templates folder, which share a name:
templates/mail/reservation_confirmed.subject Your reservation {{ code }}
templates/mail/reservation_confirmed.txt Hello {{ username }}, …
templates/mail/reservation_confirmed.html <p>Hello {{ username }}, …</p>
<name>.subjectis the subject. Only its first line is used, so the newline at the end of the file does not matter.<name>.txtis the text. It is required.<name>.htmlis the HTML version. It is optional: without it, the mail is text only.
The templates use minijinja, which has Jinja2’s syntax, close to
Django’s template language: {{ code }}, {% if %}…{% endif %},
{% for %}, filters. Values are escaped in the HTML file, and not in the
text and the subject.
The folder is read once, when the application starts. You can also give a template in code, which is handy in tests:
#![allow(unused)]
fn main() {
Mailer::from_env()?
.template("welcome", "Welcome, {{ name }}", "Hello {{ name }}!", None)
}
The last argument is the HTML, Some("…"), or None for none.
Templates of a plugin
A plugin that sends mail of its own (rind-auth sends sign-in codes and
password resets) ships default texts. It renders them with
mailer.render_or(name, defaults, context): when the application has a
template of that name, that template is used; otherwise the plugin’s
defaults are. To change the text of a plugin’s mail, put a template of
the same name in your folder. rind-auth’s are named auth_code,
auth_pwreset and auth_activate.
Choosing a transport
A transport is what carries the message. RIND_MAIL_URL picks it:
RIND_MAIL_URL | Transport | What it does |
|---|---|---|
console: (the default) | Console | writes each message to the log (target rind::mail), body included. For development only |
file:///var/mail/out | File | writes each message as an .eml file in the folder, which is created if needed |
memory: | Memory | keeps the messages in memory |
smtp://user:pass@host:587?tls=required | Smtp (feature mail-smtp) | sends through an SMTP server, with STARTTLS |
smtps://user:pass@host:465 | Smtp | the same, with TLS from the start |
smtp://host:25 | Smtp | no TLS: for a relay on the same machine |
mailgun://<api key>@<domain>?region=eu&webhook_key=… | Mailgun (feature mail-mailgun) | sends through Mailgun’s API, with tags, tracking, and its events |
A URL that needs a feature rind was built without is refused when the application starts, with a message that names the feature.
SMTP keeps a pool of connections. The password is not written to the logs. The error of a refused message says whether it is temporary or permanent, as the server’s answer does.
Mailgun sends each message to its API with its tags, its tracking
choice, and its reference (as the variable rind-reference, which
Mailgun gives back in every event). region=eu uses Mailgun’s European
servers. webhook_key is the webhook signing key: without it, the
events are refused. See Delivery events.
Testing with the Memory transport
In a test, give the mailer a Memory transport that you keep a handle
on, and read its outbox, as Django’s mail.outbox:
#![allow(unused)]
fn main() {
// sample/tests/mail.rs
let memory = rind::mail::Memory::new();
let app = sample::bare_app().with(
Mailer::new(memory.clone())
.from("The railway <noreply@railway.example>")
.templates_dir(TEMPLATES)
.unwrap(),
);
// … a request that sends mail …
assert_eq!(memory.outbox()[0].to, ["bob@railway.example"]);
}
memory.clear() empties the outbox. (RIND_MAIL_URL=memory: also
works, but the code then has no handle to read the outbox with.)
A transport of your own
A transport is one impl rind::mail::Transport, given to
Mailer::new(transport). It has a name and a send, and two optional
methods:
check, which/readycalls to see whether the transport answers;webhook, for a transport whose service posts events back.
A relay that your company already runs, or a provider rind does not know, is one of those.
Sending everything to yourself
On a staging server, you want real mail, but not to real people. Set
RIND_MAIL_REDIRECT=dev@example.org (or call .redirect(..) on the
mailer): every message then goes to that address only. The real
recipients are written at the start of the subject, [bob@example.org] Your reservation…, and in the header X-Rind-Original-To. Do not set
it in production.
What became of a message
Every message sent is a row of the table rind_mail, which the plugin
creates with its own migrations. The row has:
- the transport’s id for the message, and your reference;
- the sender, the recipients, the subject and the tags;
- its last status, when it changed, and a detail (an error, a link);
- the times it was delivered, opened and clicked.
The bodies are not kept, because they can hold sign-in codes.
mail-prune --days 90 deletes the rows older than that many days (90
when not given). Run it from a scheduled job or a cron.
If your application keeps its own record of what it sent (a
notification table, say), give the mailer a sink: .sink(MySink),
where MySink implements rind::mail::Sink (sent and event). The
table rind_mail is then not created. .no_log() records nothing at
all.
/ready asks the transport whether it answers: the SMTP server
answers, Mailgun knows the domain, the folder exists
(Health).
Delivery events
A transport like Mailgun tells you later what happened to a message. It
posts these events to a webhook of the mailer, at
/mail/events/<transport>: POST /mail/events/mailgun for Mailgun.
Give that address to Mailgun for the events you want: delivered,
opened, clicked, failed, complained, unsubscribed. (.events_path(..)
changes the /mail/events part.)
Each request is checked against the webhook signing key (an HMAC of its timestamp and token). A request whose signature does not match, or that is older than 15 minutes, is refused with a 406, which tells Mailgun not to retry it.
Each event changes the status of the message’s row:
| Mailgun’s event | Status |
|---|---|
| accepted | accepted |
| failed, temporary | deferred |
| delivered | delivered (and delivered_at) |
| opened | opened (and opened_at) |
| clicked | clicked (and clicked_at; the link is in detail) |
| failed, permanent; rejected | failed (the reason is in detail) |
| complained, unsubscribed | complained, unsubscribed |
Events can arrive out of order, so a status never goes back: a
delivered that arrives after opened leaves the row at opened. The
times (delivered_at…) are always recorded.
Sending after the write commits
mailer.send sends at once, inside the request. Two things can go
wrong with that. The request’s write may still fail after the mail went
out, and the client gets a confirmation for a booking that does not
exist. And a slow or broken mail server makes the request slow or broken.
With the jobs plugin, mailer.queue(ctx, message) queues
the message instead. The queued job is written in the request’s
transaction: a worker sends it only once the write has committed, and
tries again, up to three times, when the transport fails. The railway
confirms its reservations this way when it has the jobs plugin:
#![allow(unused)]
fn main() {
// sample/crates/booking/booking-api/src/reservations/views.rs
match ctx.service::<rind::jobs::Jobs>() {
Some(_) => {
mailer.queue(ctx, message).await?;
}
None => {
mailer.send(&ctx.db, message).await?;
}
}
}
The jobs plugin must know the job that sends mail: give it with
Jobs::new().mail(). Without the jobs plugin, queue returns an error.
Note: a queued message is kept whole, body included, in the jobs’ table
rind_job_rununtiljobs-prunedeletes it.
Not planned
Open and click tracking for SMTP (a tracking pixel, links through a redirect). Use Mailgun for that.
Reference
Mailer
| Method | What it does |
|---|---|
Mailer::from_env() | the transport of RIND_MAIL_URL, with RIND_MAIL_FROM and RIND_MAIL_REDIRECT |
Mailer::new(transport), Mailer::shared(Arc<dyn Transport>) | a mailer on a transport of your choice |
.from(sender) | the default sender |
.redirect(address) | every message to this address instead |
.templates_dir(folder) | every .subject, .txt and .html file of the folder; a template of the same name given before is replaced |
.template(name, subject, text, html) | one template, in code |
.sink(sink) | records into sink instead of rind_mail (which is then not created) |
.no_log() | records nothing |
.events_path(path) | where the webhooks are, /mail/events by default |
message(name, context) | a Message from a template |
render(name, context), render_or(name, defaults, context) | the subject, text and HTML of a template, as a Rendered |
has_template(name) | does the application have this template (its .txt)? |
send(db, message) | sends and records; gives a Sent with the transport’s id |
queue(ctx, message) | queues it with the jobs plugin; gives the run’s id |
What the plugin adds
| Table | rind_mail (domain rind_mail), unless .sink(..) or .no_log() |
| Command | mail-prune [--days n] |
| Route | POST /mail/events/<transport>, for a transport with a webhook |
| Health check | mail, in /ready |
| Service | the Mailer, for ctx.service::<Mailer>() |
| Job | rind.mail (SendMail), registered by Jobs::mail() |