# `@hamur/mail`

The first-party mail module. Add it to `modules` and set its options under the `mail` config key. It writes each message as MIME itself and hands it to one transport per app; `hamur dev` and tests write to the `outbox` instead of sending. Set the transport in `$production`: a `$development` block is merged over the file's keys, so `{ type: "outbox" }` would keep the other transport's keys and be refused.

```ts
// hamur.config.ts
import mail from "@hamur/mail"
import { defineConfig, env } from "hamur"

export default defineConfig({
  modules: [mail],
  site: { url: "https://acme.dev" },
  mail: { from: "Acme <hello@acme.dev>" },
  $production: {
    mail: {
      from: "Acme <hello@acme.dev>",
      transport: {
        type: "smtp",
        host: "smtp.postmarkapp.com",
        port: 587,
        user: env("SMTP_USER"),
        password: env("SMTP_PASSWORD"),
      },
    },
  },
})
```

### `default`

The module, as `defineModule({ meta: { name: "mail", configKey: "mail" } })`. Its setup checks the options (a wrong value is an error naming the key, such as `mail.transport.port must be an integer from 1 to 65535 (got 0)`), picks the transport, and refuses `@hamur/mail/server` in client code.

A secret (`password`, `apiKey`, `serverToken`, `accessKeyId`, `secretAccessKey`) must be `env("NAME")`: `mail.transport.password must be env("NAME"); a secret in the config file ends up in the repository`. `secure: false` is allowed for `localhost` only.

Under `hamur dev` and in tests (`NODE_ENV=test`) a missing `mail.transport` is `outbox`. A build without one fails: `@hamur/mail needs mail.transport on the node preset; outbox is for hamur dev and tests`; a build without `site.url` (or `HAMUR_SITE_URL`) fails: `@hamur/mail needs site.url: a mail holds absolute links`. An explicit `outbox` in a build warns: `mail.transport is outbox in a build: messages are written to <dir> and never sent`.

### `MailConfig`, `MailAddress`

```ts
interface MailConfig {
  from: MailAddress
  replyTo?: MailAddress
  transport?: MailTransport
  queue?: boolean
  dkim?: { domain: string; selector: string; privateKey: EnvRef }
}
type MailAddress = string | { name?: string; address: string } // "Ada <ada@x.dev>", "ada@x.dev" or the object
type MailTransport =
  | {
      type: "smtp"
      host: string
      port?: number
      secure?: "tls" | "starttls" | false
      user?: string | EnvRef
      password?: EnvRef
    }
  | { type: "resend"; apiKey: EnvRef }
  | { type: "postmark"; serverToken: EnvRef; messageStream?: string }
  | { type: "sendgrid"; apiKey: EnvRef }
  | { type: "mailgun"; apiKey: EnvRef; domain: string; region?: "us" | "eu" }
  | { type: "ses"; region: string; accessKeyId: EnvRef; secretAccessKey: EnvRef }
  | { type: "cloudflare"; binding: string }
  | { type: "outbox"; dir?: string } // default <buildDir>/mail
```

A domain that is not ASCII is kept in its IDNA form (`ada@bücher.example` is `ada@xn--bcher-kva.example`). An address holding a CR or LF is not an address. This version sends through `smtp`, `resend`, `postmark`, `sendgrid`, `mailgun`, `ses`, `cloudflare` and `outbox`.

`smtp` talks to a relay on bun, node, vercel, netlify and cloudflare. `port` defaults to 587 (465 with `secure: "tls"`), and `secure` to `"tls"` on port 465 and `"starttls"` on every other. The server's certificate is always checked; a private authority goes in `NODE_EXTRA_CA_CERTS` on bun and node. `user` and `password` are set together. With `"starttls"` a server that does not offer it gets no credentials and no mail: `smtp.example.com:587 did not offer STARTTLS; refusing to send credentials in clear text`. A connection has 10 seconds to open and each command 30 seconds to be answered. On bun and node one connection is kept for up to 30 idle seconds and used again; elsewhere each send opens and closes its own.

`dkim: { domain: "acme.dev", selector: "mail", privateKey: env("DKIM_PRIVATE_KEY") }` signs each message `smtp` sends, for a relay that does not sign: `rsa-sha256`, relaxed/relaxed, over `from`, `to`, `subject`, `date`, `message-id`, `mime-version`, `content-type` and the body. The DNS record `<selector>._domainkey.<domain>` holds the public key, and `privateKey` is the private key as `env("NAME")`, read at each send.

A key of another form fails the first send: `mail.dkim.privateKey must be a PKCS #8 RSA private key in PEM`. The other providers sign themselves, so a build with another transport warns: `mail.dkim is read by the smtp transport only`.

A build for cloudflare checks the transport: `mail.transport smtp on the cloudflare preset uses ports 465 or 587; Workers refuse port 25 (got 25)` and `mail.transport outbox writes files, which the cloudflare preset has none of`.

`cloudflare` sends through a Worker's `send_email` binding, `env[binding].send(new EmailMessage(from, to, raw))`, once for each recipient of the envelope (`to`, `cc` and `bcc`) in that order, each with the same MIME message and the envelope sender. It runs on the `cloudflare` preset only, and the build checks it: `mail.transport cloudflare runs on the cloudflare preset only (got "node")` and `mail.transport.binding "EMAIL" is not a send_email binding of the app's wrangler config; add send_email: [{ name: "EMAIL" }]`. The binding's refusal stops the send at that recipient. A refusal after the first recipient fails with `the message reached 1 of 3 recipients before one failed; sending it again delivers it twice to those 1`: the counts are in the text, an address never is, and a retry sends to every recipient again.

The HTTP providers (`resend`, `postmark`, `sendgrid`, `mailgun`, `ses`) run on every preset over `fetch`, with a 30 second timeout, and never follow a redirect. `resend`, `postmark` and `sendgrid` get the message as their JSON; `mailgun` and `ses` get the MIME message (`ses` signed with SigV4; `region` is a region name such as `"eu-west-1"`). `tags` go where the provider takes them: `resend` and `ses` tags, `sendgrid` categories, `mailgun` `o:tag`, and `postmark` its one `Tag` (the first). A non-2xx answer fails with `HTTP 422: <body>`, the body at most 500 characters with the key and the addresses it repeats left out. A timeout or a lost connection fails with `the server did not confirm the message and may have accepted it`, as for `smtp`.

### `MailMessage`, `MailResult`, `MailTemplates`

```ts
interface MailMessage<T extends keyof MailTemplates> {
  to: MailAddress | MailAddress[]
  cc?: MailAddress | MailAddress[]
  bcc?: MailAddress | MailAddress[]
  from?: MailAddress // default mail.from
  replyTo?: MailAddress // default mail.replyTo
  subject: string
  template?: T
  props?: MailTemplates[T]
  html?: string
  text?: string
  attachments?: Array<{ filename: string; content: Uint8Array | Blob | string; contentType?: string; cid?: string }>
  headers?: Record<string, string>
  tags?: string[]
}
interface MailResult {
  id: string // the Message-ID without <>
  queued: boolean
}
interface MailTemplates {} // filled in by typegen from app/mail/
```

A mail template is a component of the app's library in `app/mail/<Name>.<ext>` (a function returning a string in an html app), with a name such as `Welcome`. Layers add theirs, and the app's file wins by name. `MailTemplates` holds each template's props, so a wrong template or prop fails the type check.

```tsx
// app/mail/Welcome.tsx
export default function Welcome(props: { name: string }) {
  return (
    <div style={{ fontFamily: "system-ui", padding: "24px" }}>
      <h1 style={{ fontSize: "20px" }}>Welcome, {props.name}</h1>
      <p>
        <a href="/dashboard">Open your dashboard</a>
      </p>
    </div>
  )
}
```

```ts
import { sendMail } from "@hamur/mail/server"

await sendMail({ to: "ada@x.dev", subject: "Welcome to Acme", template: "Welcome", props: { name: "Ada" } })
```

The component renders on the server with no client script, in a document whose `lang` is `i18n.defaultLocale`, else `en`. An app path in `href` or `src` becomes an absolute URL on `site.url` and `app.baseURL`. It renders outside the request: the app's plugins do not run and the public runtime config is empty, so pass what it shows as props. Write styles inline; a build warns about a style block: `app/mail/Welcome.vue has a <style> block; mail clients drop it, so write styles inline`.

## `@hamur/mail/server`

### `sendMail`

```ts
function sendMail<T extends keyof MailTemplates>(
  message: MailMessage<T>,
  options?: { queue?: boolean; delay?: number },
): Promise<MailResult>
```

Checks the message, renders its `template`, runs the `mail:beforeSend` hook with it, checks it again, writes the MIME message and hands it to the transport inside the span `mail.send` (attributes `mail.transport` and `mail.template`, never an address). Each check is a `TypeError` thrown before anything is sent: `sendMail needs template or html (got neither)`, `sendMail takes template or html, not both`, `sendMail to[0] "ada@" is not an address`, `sendMail subject holds a line break`, `sendMail headers["x-tag"] holds a line break`, `sendMail headers cannot set "from"; use the from option` (also `to`, `cc`, `bcc`, `subject`, `reply-to`; `date`, `message-id`, `mime-version`, `content-type` and `content-transfer-encoding` say `Hamur writes it`).

A transport failure rejects with `Mail "Welcome" failed on smtp: 550 5.1.1 Recipient address rejected` (`Mail html failed on …` without a template), the transport's error as `cause`; what the server repeats of the addresses is left out, and the span records none of its text. `the server did not confirm the message and may have accepted it` is not a refusal: the connection was lost after the whole message was sent, so sending it again may deliver it twice.

Without `text`, the text part is written from the HTML: one line per block element, `- ` before a list item, `text (url)` for a link and the `alt` of an image.

The MIME message is `multipart/alternative` of `text/plain` and `text/html` (UTF-8 quoted-printable), inside `multipart/related` when an attachment has a `cid` and inside `multipart/mixed` for the other attachments (base64 in 76-column lines, `filename*=UTF-8''…`). Header text that is not ASCII is written as RFC 2047 encoded words; lines end in CRLF and none passes 998 octets. `Bcc` is never written into the message.

The `outbox` transport writes `<dir>/<ISO time>-<id>.eml` and `.json` (`{ id, date, from, to, cc, bcc, subject, template?, html, text, headers, attachments: [{ filename, contentType, size }] }`) and keeps the newest 200 pairs. Under `hamur dev` each send logs `[mail] html → ada@x.dev (open in devtools: <url>)`.

Server hooks: `mail:beforeSend(message, { event })`, which may change the message (headers, `bcc`); `mail:sent(result, message)`; `mail:error(error, message)`. Use `mail:error` to report a failure, never to send the mail again: after a direct call `sendMail` rejects to its caller, who can, and a queued mail may be sent again by its queue, so the recipient would get it twice. `message` is the rendered one, with `html` and, for a templated mail, `template`: `sendMail` refuses the two together.

#### Queued mail

```ts
await sendMail({ to: "ada@x.dev", subject: "Welcome to Acme", template: "Welcome", props }, { queue: true, delay: 60 })
```

With `queue: true`, or `mail.queue: true` in the config for every call that does not pass `queue: false`, the call checks and renders the message, so a template error throws there, and hands it to the task `mail:send` through [`enqueue`](/tasks). It resolves to `{ id, queued: true }` once the queue took it. `delay` is `enqueue`'s, in whole seconds; without the queue it is a `TypeError`: `sendMail delay needs queue: true`.

- **Retries.** A message that the transport refused fails the task, so the retries of Cloudflare's and Vercel's queue apply (`tasks.queue`). Without a queue the run is in process: it is not retried, and a restart loses it.
- **No retry that may deliver twice.** After a failure that leaves open whether a recipient got the message (`the server did not confirm the message and may have accepted it`, or an HTTP 5xx other than 503) the task does not fail: it logs `Mail "Welcome" failed on smtp: …; the queue does not send it again` at `error`. Whether to send it again is for a person who read that line to decide. A queue itself delivers at least once, so in rare cases it runs the task twice; the mail is then sent twice.
- **Size.** Attachments travel with the message, and Cloudflare Queues take 128 KB: a larger one fails at the call with `enqueue payload is 188 KB; Cloudflare Queues take 128 KB`. Store a large attachment as a blob, `enqueue` a task of your own with its key, and have that task read the blob and call `sendMail` with `queue: false`. There `sendMail` rejects after every failure, so the task decides which ones it lets the queue retry.

`mail:beforeSend` runs in the call; `mail:sent` and `mail:error` run in the task, `mail:error` once for each failed attempt. An error they throw there is logged and does not send the message again. The task's error, which the log, the spans and `hamur task failed` show, has the reason without the addresses. A queued message holds the mail as rendered and none of the transport's secrets.

## `@hamur/mail/test`

### `sentMail`, `clearSentMail`, `MailRecord`, `SentMailOptions`

```ts
import { clearSentMail, sentMail } from "@hamur/mail/test"

function sentMail(options?: SentMailOptions): Promise<MailRecord[]>
function clearSentMail(options?: SentMailOptions): Promise<void>
interface SentMailOptions {
  dir?: string // the outbox directory, default the test app's or the test preload's
}
interface MailRecord {
  id: string
  date: string
  from: string
  to: string[]
  cc: string[]
  bcc: string[]
  subject: string
  template?: string
  html: string
  text: string
  headers: Record<string, string>
  attachments: Array<{ filename: string; contentType: string; size: number }>
}
```

`sentMail` returns the outbox's `.json` files, oldest first; `clearSentMail` removes every `.eml` and `.json` of it. Both read the outbox of the test app `setup` built (`<build dir>/mail`), or without one the outbox of the test preload's build dir, so a mail sent by a built app, by `callHandler` or by `renderPage` is found the same way. A queued mail is written before `sendMail` resolves there, whatever its `delay`: no queue is used. A missing directory is an empty outbox. Without `setup` and without the preload they throw `@hamur/mail/test: no outbox to read; call setup() from hamur/test in this file or run the tests with the hamur/test/preload`.

`setup` and the test preload build the app with the `outbox` transport whatever `mail.transport` says, `dir` included, so a test never sends.

## `@hamur/mail/devtools`

The view of the `mail` tab of `@hamur/devtools`, which the module registers with `addDevtoolsTab` in `hamur dev`; an app never imports it. The **Outbox** part lists the messages of the `outbox` transport newest first and shows the selected one: its HTML in an `<iframe sandbox>` (no scripts, no same-origin access) whose document starts with `Content-Security-Policy: default-src 'none'; img-src * data:; style-src 'unsafe-inline'`, its text part, its headers, and a download of the `.eml`. The **Templates** part lists the `app/mail/` templates, renders one with the props typed as JSON and shows its HTML and text; rendering sends nothing. With another transport the outbox part says `The outbox is off: mail.transport is <type>`.

The tab calls these functions with `ctx.rpc` (they run in `hamur dev` only):

| Function         | Arguments              | Answer                                                                                                                                                 |
| ---------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `mail:list`      |                        | `{ transport, messages: [{ name, date, from, to, subject, template? }] }`, newest first                                                                |
| `mail:message`   | `{ name }`             | `{ record, eml }`, the outbox's `.json` and `.eml`; a `name` the outbox does not list rejects `No message "<name>" in the outbox`                      |
| `mail:templates` |                        | `{ templates: string[] }`                                                                                                                              |
| `mail:render`    | `{ template, props? }` | `{ html, text }`; nothing is sent. An unknown template rejects `No mail template "<name>"`, props that are not an object `props must be a JSON object` |

The server side of `mail:render` is the route `POST <app.baseURL>_hamur/devtools/api/mail/render` that the module's door adds in `hamur dev` only, behind the devtools' dev data route rule, since templates render in the SSR process. The devtools socket carries the event `devtools:mail` with `{ messages }`, the same list as `mail:list`, each time the outbox directory changes.
