Skip to content

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.

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.

fn send(mailer: self, message: Message) -> Result<Unit, Error>

interface Mailer

Sends message to every recipient, or fails without sending it.

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.

impl Debug for Message

fn inspect(value: Message) -> String

impl Debug.inspect

impl Equatable for Message

fn equal(a: Message, b: Message) -> Bool

impl Equatable.equal

struct Attachment
    filename: String
    content_type: String
    data: Bytes
end

A file sent with a message.

impl Debug for Attachment

fn inspect(value: Attachment) -> String

impl Debug.inspect

impl Equatable for Attachment

fn equal(a: Attachment, b: Attachment) -> Bool

impl Equatable.equal

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>"
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"))
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>"))
fn email(address: Address) -> String

type function on Address

The address, such as ada@example.com.

fn name(address: Address) -> Maybe<String>

type function on Address

The display name, or None when there is none.

impl Display for Address

fn to_string(address: Address) -> String

impl Display.to_string

impl Debug for Address

fn inspect(value: Address) -> String

impl Debug.inspect

impl Equatable for Address

fn equal(a: Address, b: Address) -> Bool

impl Equatable.equal

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

  • InvalidAddress

    An address std does not accept, and why.

  • InvalidMessage

    A message no mailer can send: no recipient, no body, a reserved or malformed header, or a malformed attachment.

  • Network

    The connection could not be made or broke: refused, reset, timed out, or TLS failed.

  • Rejected

    The server replied to command with a failure code.

  • Protocol

    The server cannot do what the config requires (STARTTLS, an AUTH mechanism std speaks), or replied with something that is not SMTP.

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"})

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"

impl Debug for Error

fn inspect(value: Error) -> String

impl Debug.inspect

impl Equatable for Error

fn equal(a: Error, b: Error) -> Bool

impl Equatable.equal

enum Security
    StartTls
    StartTlsIfOffered
    Tls
    Off
end

How an SMTP connection is protected.

Variants

  • StartTls

    Upgrade with STARTTLS, and fail with Protocol if the server does not offer it. Servers take it on port 587, SmtpConfig’s default.

  • StartTlsIfOffered

    Upgrade with STARTTLS when the server offers it, else send in the clear.

  • Tls

    TLS from the first byte. Servers take it on port 465, which SmtpConfig.port must then name.

  • Off

    No TLS, for a local catcher such as Mailpit.

impl Debug for Security

fn inspect(value: Security) -> String

impl Debug.inspect

impl Equatable for Security

fn equal(a: Security, b: Security) -> Bool

impl Equatable.equal

struct Credentials
    username: String
    password: String
end

A username and password for SMTP AUTH.

impl Debug for Credentials

fn inspect(value: Credentials) -> String

impl Debug.inspect

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.

impl Debug for SmtpConfig

fn inspect(value: SmtpConfig) -> String

impl Debug.inspect

struct Smtp

opaque — construction surface is private to its defining module

A mailer that sends through an SMTP server, one connection per message.

impl Mailer for Smtp

fn send(smtp: Smtp, message: Message) -> Result<Unit, Error>

impl Mailer.send

impl Debug for Smtp

fn inspect(value: Smtp) -> String

impl Debug.inspect

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.

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.

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")
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"
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==?="]
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"
fn recipients(message: Message) -> List<String>

The envelope’s recipients: every address in to, cc and bcc, each once, in that order.