# Mail

Sending mail from the back end through a mail service's HTTP API:
[Resend](https://resend.com), or Cloudflare Email Service, chosen by a
setting, behind one `mailSend`, so that a program is not tied to either. A
suppression list that every send consults, kept by Resend's events. Bodies
from Markdown. An [extension](../extensions/README.md): ordinary Mote in
`extensions/mail/`, over [`net.send`](data.md#netsend) and
[`secret`](back-end.md#secrets). Back to the [map](README.md). Reading mail
(a message's parts, an mbox, addresses) is the same extension's
[library](mail-library.md).
([Sending mail](back-end.md#sending-mail) in back-end.md is the same thing
by hand, for any service.)

```mote
use "pkg:mail/mail.mote"
use "pkg:mail/webhooks.mote"

job fn receipt(order: id) retries=5
  let o = Order.get(order)?
  let body = mailMarkdown(`# Thank you\n\nYour order of **${o?.item}** is on its way.`)?
  mailSend({to: [o?.email ?? ""], subject: "Your order", html: body.html, text: body.text, key: `receipt-${order}`})?
```

```toml
[packages]
mail = "../mote/extensions/mail"
```

```sh
MAIL_KEY=re_… MAIL_FROM="Shop <hello@shop.example>" MAIL_WEBHOOK_SECRET=whsec_… bun dist/server/main.js
# or
MAIL_PROVIDER=cloudflare MAIL_ACCOUNT=<account id> MAIL_KEY=<API token> MAIL_FROM=hello@shop.example bun dist/server/main.js
```

**Neither service has been met.** Both were written from their API
references and run against stand-ins that speak their shapes
(`tests/svc_standin.mjs resend`, `… cloudflare`). The steps to check each
with a real key are [below](#checking-it-against-the-services).

## The settings

| | |
|---|---|
| `MAIL_PROVIDER` | `resend` (unsaid), `cloudflare`, or `smtp` ([below](#smtp)); `ses` with the aws extension's `pkg:aws/ses.mote` ([aws.md](aws.md)), `gmail` with the gcloud extension's `pkg:gcloud/gmail.mote` ([gcloud.md](gcloud.md)), `azure` with `pkg:azure/email.mote` ([azure.md](azure.md)): each declares the fn `mail.mote` wants for it (`mailViaSes`, `mailViaGmail`, `mailViaAzure`). |
| `MAIL_KEY` | Resend's API key (`re_…`), a Cloudflare API token that may send email, or the SMTP password. A secret that may be unset (SES and Gmail sign in their own way): a send that needs it fails with `auth` and "Set MAIL_KEY". The log never holds it. |
| `MAIL_FROM` | Who a message is from when it does not say. Its domain must be one the service has verified. |
| `MAIL_ACCOUNT` | For Cloudflare: the account's id. |
| `MAIL_WEBHOOK_SECRET` | With `webhooks.mote`: Resend's signing secret for the endpoint (`whsec_…`). A secret. |
| `MAIL_API` | Another address for the API (a stand-in, in tests). |

## Sending

`mailSend(m: MailMessage): MailSent`. A message:

| Field | |
|---|---|
| `to` | Addresses, `"ada@shop.example"` or `"Ada <ada@shop.example>"`. Also `cc`, `bcc`, `replyTo`. |
| `subject`, `html`, `text` | One of `html` and `text` at least; `mailMarkdown` makes both. |
| `from` | Unsaid: `MAIL_FROM`. |
| `attachments` | `MailFile`s: `{name, data, type?, inline?}`; `data` is bytes, sent as base64. `inline: "logo"` is `<img src="cid:logo">` (Resend). |
| `tags` | `{name, value}`s Resend keeps with the message (letters, digits, `_`, `-`). Cloudflare has none: they are not sent there. |
| `headers` | `{name, value}`s: `List-Unsubscribe`, `In-Reply-To`. |
| `at` | A moment to send it at (Resend). Cloudflare sends at once, and refuses one with `at`. |
| `key` | An idempotency key that names the message (`receipt-${order}`): sent twice, it goes once. Unsaid, a fresh one, which still makes the call's own tries one message. |

What comes back: `{id, provider, to, suppressed}`: the service's id, who it
went to, and who was left out.

- **Every address is checked first**: one `@`, no space, no line end (no
  header slips in through an address). A message with nothing to say, or
  no `from`, is refused before anything is sent.
- **Tried again** on 429 and 5xx, after what `Retry-After` says, with the
  same idempotency key ([net.send](data.md#netsend)).
- Mail that must not be lost is sent from a [`job fn`](back-end.md#later-job-fn)
  with a `key` of its own, as above: queued with the write it follows, kept
  across a restart, and once however often the job runs.
- `mailBatch(messages)`: Resend's batch, one request for up to a hundred
  (none with attachments or `at`, which its batch does not take: those, and
  every message at Cloudflare, are sent one by one). A message all of whose
  addresses are suppressed has `id: ""` in its place.
- `mailCancel(id)`: takes back a message sent with `at`, before its time.

| Kind | |
|---|---|
| `"suppressed"` | Every address it was for is on the suppression list: nothing was sent. `err.data.suppressed`. |
| `"invalid"` | The message was refused before sending, or the service did not take it (its words follow "The mail service did not take the message:"). |
| `"auth"` | The key is wrong, or may not send from that address. |
| `"limited"` | Too many (or a day's quota), after the tries. |
| `"mail"` | The service broke, after the tries. |
| `"offline"` | It did not answer. |

## SMTP

`MAIL_PROVIDER=smtp` sends by SMTP (`extensions/mail/smtp.mote`, on
[`tcp.open`](back-end.md#connections-of-its-own)) to any mail server: a
relay of your own, or the SMTP endpoint of Postmark, SES, Mailgun,
SendGrid, Fastmail, Google Workspace.

| | |
|---|---|
| `MAIL_SMTP` | `smtps://user@smtp.example.com:465`: TLS from the first byte; or `smtp://user@smtp.example.com:587`: STARTTLS, which is then required (a server that offers none is refused with a sentence: a password is never sent in the clear). `?tls=none` for a relay on this machine that has no TLS; `?addr=10.0.0.5` to connect to an address while the certificate is the host's; `?helo=` the name it says it is. |
| `MAIL_KEY` | The password (a secret). Sent by AUTH PLAIN, or LOGIN where that is all the server offers. |
| `MAIL_SMTP_CA` | The authority that signs the server's certificate (PEM), when this machine's do not. |

The message is built here (RFC 5322 and MIME): `From`, `To`, `Cc`,
`Reply-To`, `Subject` (non-ASCII as RFC 2047's encoded words), `Date`,
`Message-ID`, the message's own `headers`; text and HTML as alternatives;
each attachment (an `inline` one with its `Content-ID`, for `cid:`); every
part in base64, so that any text goes through any server. `bcc` is sent to
and not written. A recipient the server refuses is left out of what
`mailSend` gives (`to`), and logged with why; when it refuses them all, the
send fails (`invalid`). A wrong password is `auth` (535); a refusal that
says "try later" (4xx) is `limited`; another, `invalid`. SMTP has no
idempotency key: a message is sent once per call, and `mailSend` is not
tried again by itself. `at` (a time to send) is Resend's alone.

**Checked only against a stand-in** (`tests/smtp_standin.mjs`,
`tests/all.sh real_svc_smtp`): STARTTLS at 587, implicit TLS at 465, AUTH,
the message as it arrived (its head, its parts decoded), a recipient
refused, a wrong password, a server with no STARTTLS. To check it with a
real server: set `MAIL_PROVIDER=smtp`, `MAIL_SMTP` and `MAIL_KEY` for an
account of yours, `MAIL_FROM` one of its addresses, and send yourself a
message with an attachment and a `cid:` picture; read its source in your
mail program.

## The suppression list

`MailSuppressed`: addresses no message goes to. `mailSend` leaves them out
of `to`, `cc` and `bcc` (and says so in `suppressed`); a message for none
but them fails with `kind "suppressed"`. Sending to an address that bounced
for good, again and again, is what gets a sender's mail put in spam.

- Resend's events put them there (below): a permanent bounce, a complaint.
- Cloudflare says, as it sends, which addresses bounced for good
  (`permanent_bounces`): those go on the list then. It keeps its own list
  too (`suppressed_recipients`), and both are in `suppressed`.
- `mailSuppress(address, why, detail)`, `mailUnsuppress(address)`,
  `mailIsSuppressed(address)`: the program's own (an unsubscribe link, an
  admin taking one off after the person fixed their mailbox).

## Resend's events: webhooks.mote

`POST /mail/resend/webhook`. Resend sends its events through Svix, signed
as Svix signs: `svix-signature` holds one or more `v1,<base64>`, each the
HMAC-SHA256 of `<svix-id>.<svix-timestamp>.<body>` under the bytes of the
secret (after `whsec_`, read as base64). The route checks it with
[`webhook.check(req, "resend", …)`](back-end.md#webhooks) (each compared in
constant time, a timestamp more than five minutes off refused), keeps each
`svix-id` once (a week), and then ([Polar](polar.md)'s events, signed the same way, are
checked by the same `webhook.check`):

- `email.bounced` that is not `Transient` → the address is suppressed
  (`why: "bounced"`, with what the receiving server said);
- `email.complained` → suppressed (`why: "complained"`);
- every event → `fn mailHeard(e: MailEvent): bool`, if the program declares
  it: `{type, email, to, subject, bounce, detail, data}`.

At Resend: Webhooks → add an endpoint at `https://<the site>/mail/resend/webhook`
with `email.delivered`, `email.bounced`, `email.complained`.

## Markdown

`mailMarkdown(markdown): MailBody` is `{html, text}` from one document read
by `syntax.parse(text, "markdown")` (the reader of the kit's `Markdown`), on
the back end: the HTML with each element's style written on it (many mail
programs drop a `<style>` block), raw HTML in the text kept as text, links
only to http, https, mailto and tel; the plain text with each link's address
after its words.

## Checking it against the services

Resend, with an account and a domain it has verified:

1. An API key (Sending access) is `MAIL_KEY`; `MAIL_FROM` an address at
   that domain. Send one message to yourself: `mailSend` gives an `id`, and
   the message is in Resend's Emails page with its tags.
2. Send to `bounced@resend.dev` (Resend's test address that bounces) with
   the webhook set up: the event arrives, the route answers 200, and the
   address is in `MailSuppressed`. `complained@resend.dev` likewise.
3. A message with `at` an hour away shows as scheduled; `mailCancel(id)`
   takes it back.
4. Send the same message with one `key` twice: one message.

Cloudflare Email Service, with a domain on Cloudflare set up for sending:

1. `MAIL_PROVIDER=cloudflare`, `MAIL_ACCOUNT` the account's id, `MAIL_KEY`
   an API token with the right to send email.
2. Send one message to yourself, with an attachment: `mailSend` gives the
   `message_id`. Compare the fields Cloudflare took with the body in
   `mailCloudflareBody` (`from`, `to`, `cc`, `bcc`, `reply_to`, `subject`,
   `html`, `text`, `headers`, `attachments` of `{content, filename, type,
   disposition}`): these were read from its API reference.
3. Whether Cloudflare keeps an `Idempotency-Key` is not known here: it is
   sent; check that a second send with the same key is one message, or rely
   on a `job fn` that sends once.

Recorded in `tests/expect/real_svc_mail.txt` (`tests/all.sh
real_svc_mail`): the same messages through both stand-ins, what each was
sent, a refusal, Markdown, a batch, a message for later taken back, a
permanent bounce at Cloudflare, Resend's events signed, refused, sent twice,
into the list; and the extension's own `mote test`.
