std::mail
Sending email. A Message is one struct literal. Code that sends mail
calls the Mailer interface, so one function sends through an SMTP
server in production and into a test’s std::mail::testing.Memory:
fn send_login_link(email: String, link: Url) -> Result<Unit, mail.Error> message = Message{ from: Address.parse("Updates <no-reply@example.com>")?, to: [Address.new(email)?], subject: "Your login link", text: Some("Open ${link} to log in."), html: Some(Html"<p><a href='${link}'>Log in</a></p>"), } Mailer.send(App.mailer, message) end
mail.smtp is a mailer for any SMTP server: a provider’s relay
(Mailgun, Postmark, SES), a company relay, or a local catcher such as
Mailpit. Boot code makes one:
mailer = mail.smtp(SmtpConfig{ host: "smtp.mailgun.org", credentials: Some(Credentials{username: login, password: secret}), })
std::mail::testing has Memory, a mailer that keeps what it sends for
tests, Failing, a mailer whose every send fails, with_smtp_server,
an SMTP server for tests, and conformance, the suite every backend
passes.
Every mailer writes a message with mail.render: headers that cannot
be injected into, RFC 2047 encoded words for text that is not plain
ASCII, quoted-printable UTF-8 bodies, multipart/alternative for text
and HTML together, and CRLF line ends. A limit on how fast mail goes
out belongs to the caller: std::jobs’s Rate limits sends from jobs.
Import with import std::mail.
Exports
Section titled “Exports”interface Mailer
Section titled “interface Mailer”interface Mailer fn send(mailer: self, message: Message) -> Result<Unit, Error> end
Something that sends messages. mail.smtp and
std::mail::testing.Memory implement it.
Mailer.send
Section titled “Mailer.send”fn send(mailer: self, message: Message) -> Result<Unit, Error>
interface Mailer
Sends message to every recipient, or fails without sending it.
struct Message
Section titled “struct Message”struct Message from: Address to: List<Address> = [] cc: List<Address> = [] bcc: List<Address> = [] reply_to: List<Address> = [] subject: String = "" text: Maybe<String> = None html: Maybe<Html> = None headers: List<(String, String)> = [] attachments: List<Attachment> = [] end
One email.
Message.inspect
Section titled “Message.inspect”impl Debug for Message
fn inspect(value: Message) -> String
impl Debug.inspect
Message.equal
Section titled “Message.equal”impl Equatable for Message
fn equal(a: Message, b: Message) -> Bool
impl Equatable.equal
struct Attachment
Section titled “struct Attachment”struct Attachment filename: String content_type: String data: Bytes end
A file sent with a message.
Attachment.inspect
Section titled “Attachment.inspect”impl Debug for Attachment
fn inspect(value: Attachment) -> String
impl Debug.inspect
Attachment.equal
Section titled “Attachment.equal”impl Equatable for Attachment
fn equal(a: Attachment, b: Attachment) -> Bool
impl Equatable.equal
struct Address
Section titled “struct Address”struct Address
opaque — construction surface is private to its defining module
A mailbox: an address and an optional display name, checked when it is
made. The address is ASCII: a dot-atom before the @ and host-name
labels after it.
a = Address.parse("Ada Lovelace <ada@example.com>")?
assert Address.email(a) == "ada@example.com"
assert Address.name(a) == Some("Ada Lovelace")
assert "${a}" == "Ada Lovelace <ada@example.com>"
Address.new
Section titled “Address.new”fn new(email: String, name: String = "") -> Result<Address, Error>
type function on Address
The address email, with name shown beside it when it is not
empty, or Err(.InvalidAddress) saying what is wrong with email.
assert Result.is_ok(Address.new("a.b+tag@mail.example.com", name: "Ana"))
assert Result.is_ok(Address.new("dev@localhost"))
assert Address.new("no at sign")
== Err(Error.InvalidAddress{address: "no at sign", reason: "it has no @"})
assert Result.is_err(Address.new("a..b@example.com"))
assert Result.is_err(Address.new("a@-example.com"))
assert Result.is_err(Address.new("ö@example.com"))
assert Result.is_err(Address.new("a@example.com>\r\nBcc: x@y.z"))
Address.parse
Section titled “Address.parse”fn parse(text: String) -> Result<Address, Error>
type function on Address
An address as a person writes it: ada@example.com,
Ada <ada@example.com> or "Lovelace, Ada" <ada@example.com>.
Text of none of these forms is Err(.InvalidAddress).
assert Address.name(Address.parse("\"Lovelace, Ada\" <n@x.org>")?) == Some("Lovelace, Ada")
assert Address.name(Address.parse(" n@x.org ")?) == None
assert Result.is_err(Address.parse("Ada n@x.org>"))
Address.email
Section titled “Address.email”fn email(address: Address) -> String
type function on Address
The address, such as ada@example.com.
Address.name
Section titled “Address.name”fn name(address: Address) -> Maybe<String>
type function on Address
The display name, or None when there is none.
Address.to_string
Section titled “Address.to_string”impl Display for Address
fn to_string(address: Address) -> String
impl Display.to_string
Address.inspect
Section titled “Address.inspect”impl Debug for Address
fn inspect(value: Address) -> String
impl Debug.inspect
Address.equal
Section titled “Address.equal”impl Equatable for Address
fn equal(a: Address, b: Address) -> Bool
impl Equatable.equal
enum Error
Section titled “enum Error”enum Error InvalidAddress { address: String, reason: String } InvalidMessage { reason: String } Network { reason: String } Rejected { command: String, code: Int, reply: String } Protocol { reason: String } end
Why a message could not be sent.
Variants
-
InvalidAddressAn address std does not accept, and why.
-
InvalidMessageA message no mailer can send: no recipient, no body, a reserved or malformed header, or a malformed attachment.
-
NetworkThe connection could not be made or broke: refused, reset, timed out, or TLS failed.
-
RejectedThe server replied to
commandwith a failurecode. -
ProtocolThe server cannot do what the config requires (STARTTLS, an AUTH mechanism std speaks), or replied with something that is not SMTP.
Error.is_temporary
Section titled “Error.is_temporary”fn is_temporary(error: Error) -> Bool
type function on Error
Whether sending again later may succeed: a network failure or a
4xx reply. A job that sends mail can return Failure.Retry for these
and Failure.Discard for the rest.
assert Error.is_temporary(Error.Rejected{command: "RCPT TO", code: 421, reply: "busy"})
refute Error.is_temporary(Error.Rejected{command: "RCPT TO", code: 550, reply: "no such user"})
assert Error.is_temporary(Error.Network{reason: "reset"})
Error.to_string
Section titled “Error.to_string”impl Display for Error
fn to_string(error: Error) -> String
impl Display.to_string
assert "${Error.Rejected{command: "RCPT TO <a@b.c>", code: 550, reply: "no such user"}}"
== "the mail server rejected RCPT TO <a@b.c>: 550 no such user"
Error.inspect
Section titled “Error.inspect”impl Debug for Error
fn inspect(value: Error) -> String
impl Debug.inspect
Error.equal
Section titled “Error.equal”impl Equatable for Error
fn equal(a: Error, b: Error) -> Bool
impl Equatable.equal
enum Security
Section titled “enum Security”enum Security StartTls StartTlsIfOffered Tls Off end
How an SMTP connection is protected.
Variants
-
StartTlsUpgrade with STARTTLS, and fail with
Protocolif the server does not offer it. Servers take it on port 587,SmtpConfig’s default. -
StartTlsIfOfferedUpgrade with STARTTLS when the server offers it, else send in the clear.
-
TlsTLS from the first byte. Servers take it on port 465, which
SmtpConfig.portmust then name. -
OffNo TLS, for a local catcher such as Mailpit.
Security.inspect
Section titled “Security.inspect”impl Debug for Security
fn inspect(value: Security) -> String
impl Debug.inspect
Security.equal
Section titled “Security.equal”impl Equatable for Security
fn equal(a: Security, b: Security) -> Bool
impl Equatable.equal
struct Credentials
Section titled “struct Credentials”struct Credentials username: String password: String end
A username and password for SMTP AUTH.
Credentials.inspect
Section titled “Credentials.inspect”impl Debug for Credentials
fn inspect(value: Credentials) -> String
impl Debug.inspect
struct SmtpConfig
Section titled “struct SmtpConfig”struct SmtpConfig host: String port: Int = 587 security: Security = Security.StartTls credentials: Maybe<Credentials> = None hello: String = "localhost" timeout: Duration = Duration.seconds(30) tls: ClientConfig = ClientConfig{} end
Where an SMTP server is and how to reach it.
SmtpConfig.inspect
Section titled “SmtpConfig.inspect”impl Debug for SmtpConfig
fn inspect(value: SmtpConfig) -> String
impl Debug.inspect
struct Smtp
Section titled “struct Smtp”struct Smtp
opaque — construction surface is private to its defining module
A mailer that sends through an SMTP server, one connection per message.
Smtp.send
Section titled “Smtp.send”impl Mailer for Smtp
fn send(smtp: Smtp, message: Message) -> Result<Unit, Error>
impl Mailer.send
Smtp.inspect
Section titled “Smtp.inspect”impl Debug for Smtp
fn inspect(value: Smtp) -> String
impl Debug.inspect
mail.smtp
Section titled “mail.smtp”fn smtp(config: SmtpConfig) -> Smtp
A mailer for the SMTP server config describes. Nothing connects until
a message is sent.
import std::mail::testing.{SmtpServer, with_smtp_server} message = Message{ from: Address.new("a@example.com")?, to: [Address.new("b@example.com")?], text: Some("hi"), } rejected = {..message, to: [Address.new("reject-me@example.com")?]} credentials = Credentials{username: "u", password: "p"} answers = with_smtp_server(fn server -> config = SmtpServer.config(server) [ Mailer.send(smtp(config), message), Mailer.send(smtp(config), rejected), Mailer.send(smtp({..config, security: Security.StartTls}), message), Mailer.send(smtp({..config, security: Security.StartTlsIfOffered}), message), Mailer.send(smtp({..config, credentials: Some(credentials)}), message), ] end) assert [ Ok(_), Err(Error.Rejected{command: "RCPT TO <reject-me@example.com>", code: 550, reply: _}), Err(Error.Protocol{reason: _}), Ok(_), Err(Error.Protocol{reason: _}), ] = answers wrong = with_smtp_server(starttls: True, credentials: Some(credentials), fn server -> config = SmtpServer.config(server) Mailer.send(smtp({..config, credentials: Some({..credentials, password: "x"})}), message) end) assert Err(Error.Rejected{command: "AUTH PLAIN", code: 535, reply: _}) = wrong remote = SmtpConfig{ host: "mail.example.com", security: Security.Off, credentials: Some(credentials), } assert Err(Error.Protocol{reason: _}) = Mailer.send(smtp(remote), message)
Not run here: this example opens network connections and serves network requests, which a browser cannot do. nomi test runs it.
mail.deliver
Section titled “mail.deliver”fn deliver(config: SmtpConfig, from: String, recipients: List<String>, data: String) -> Result<Unit, Error>
Sends data, a rendered message, from from to recipients over an
SMTP connection config describes. Smtp.send is render and then
this.
mail.render
Section titled “mail.render”fn render(message: Message, message_id: Maybe<String> = None, date: Maybe<Instant> = None) -> Result<String, Error>
message as the text a server receives: headers, a blank line and the
body, every line ending in CRLF and all of it 7-bit ASCII. Every
mailer writes a message this way. message_id and date are made
when they are None: a random id at the From address’s domain, and
the time now.
import std::html.Html
import std::instant.Instant
message = Message{
from: Address.new("a@example.com", name: "Ana")?,
to: [Address.new("b@example.com")?],
bcc: [Address.new("c@example.com")?],
subject: "Hello",
text: Some("Hi B.\n"),
html: Some(Html"<p>Hi B.</p>"),
}
text = render(message, message_id: Some("<1@example.com>"), date: Some(Instant.from_seconds(0)))?
assert text == String.join([
"Date: Thu, 01 Jan 1970 00:00:00 +0000",
"From: Ana <a@example.com>",
"To: b@example.com",
"Subject: Hello",
"Message-ID: <1@example.com>",
"MIME-Version: 1.0",
"Content-Type: multipart/alternative; boundary=\"=_nomi_alternative\"",
"",
"--=_nomi_alternative",
"Content-Type: text/plain; charset=utf-8",
"Content-Transfer-Encoding: quoted-printable",
"",
"Hi B.",
"",
"--=_nomi_alternative",
"Content-Type: text/html; charset=utf-8",
"Content-Transfer-Encoding: quoted-printable",
"",
"<p>Hi B.</p>",
"--=_nomi_alternative--",
"",
], "\r\n")
mail.quoted_printable
Section titled “mail.quoted_printable”fn quoted_printable(text: String) -> String
text as quoted-printable: printable ASCII as it is, every other byte
of its UTF-8 as =XX, each line break as CRLF, whitespace that ends a
line encoded, and no line longer than 76 characters. It is Go’s
quotedprintable.Writer.
assert quoted_printable("a=b ö") == "a=3Db =C3=B6"
assert quoted_printable("end \nnext") == "end=20\r\nnext"
assert quoted_printable(String.repeat("x", 80)) == "${String.repeat("x", 75)}=\r\nxxxxx"
mail.encoded_words
Section titled “mail.encoded_words”fn encoded_words(text: String) -> List<String>
text as RFC 2047 encoded words, base64 UTF-8, cut between graphemes
so that each word is at most 64 characters.
assert encoded_words("Grüße") == ["=?utf-8?b?R3LDvMOfZQ==?="]
mail.rfc5322_date
Section titled “mail.rfc5322_date”fn rfc5322_date(at: Instant) -> String
at as an RFC 5322 date in UTC.
import std::instant.Instant
assert rfc5322_date(Instant.from_seconds(1793638245)) == "Mon, 02 Nov 2026 16:50:45 +0000"
assert rfc5322_date(Instant.from_seconds(951782400)) == "Tue, 29 Feb 2000 00:00:00 +0000"
mail.recipients
Section titled “mail.recipients”fn recipients(message: Message) -> List<String>
The envelope’s recipients: every address in to, cc and bcc, each once, in that order.