# Mail

`@hamur/mail` sends mail from your server code. You write a message, hamur server turns it into a mail with a text part and an HTML part, and one **transport** hands it to a mail service. While you work, mail is not sent at all: it is written to a folder you can read.

This page starts with one mail that arrives and adds one need at a time: a transport for your host, a template in your UI library, a queue, signing, and tests. It does not repeat the [`@hamur/mail` reference](/api-reference/mail), which lists every option and error message. The mail that [account links](/auth#account-links-with-hamurmail) send, such as a password reset, uses this module too.

## Send your first mail

Install the module with `hamur module add mail`, which also lists it in `modules` ([CLI](/cli#hamur-module)), and set two things: who mail comes `from`, and the public address of your site, `site.url`. A mail holds links, and a link in a mail must be absolute, so the module needs to know your address.

````ts [platform/mail-resend.ts]
import mail from "@hamur/mail"
import { defineConfig, env } from "hamur"

const from = "Acme <hello@acme.example>"

export default defineConfig({
  framework: "react",
  modules: [mail],
  site: { url: "https://acme.example" },
  mail: { from },
  $development: { site: { url: "http://localhost:3000" } },
  $production: { mail: { from, transport: { type: "resend", apiKey: env("RESEND_API_KEY") } } },
})
````

Read the config top to bottom:

- **`mail.from`** is the sender. Use an address on a domain you own. A mail service refuses to send for a domain you have not proved to be yours.
- **`site.url`** is where your links point. It is never taken from a request, because whoever sends a request chooses its `Host` header. `$development` sets it for `hamur dev`, where the site runs on `localhost`.
- **The transport** is in `$production`, so it applies to builds and not to `hamur dev` or tests. With no transport, `hamur dev` and tests write to the outbox. A build with no transport fails, so a mail can never go nowhere by accident: `@hamur/mail needs mail.transport on the node preset; outbox is for hamur dev and tests`.
- **The key is `env("RESEND_API_KEY")`**, a reference to an environment variable, never the key. A key written in the config would end up in your repository, so the module refuses it: `mail.transport.apiKey must be env("NAME"); a secret in the config file ends up in the repository`.

Put the transport in `$production` on purpose. A `$development` block is merged over the file's keys, so `{ type: "outbox" }` over a Resend transport would keep its `apiKey`, and the module would refuse the result.

**Declare the variable.** Every `env("NAME")` in the config must name an entry of `app/env.ts`, or the build stops at once: `HAMUR_E1244 mail.transport.apiKey reads env "RESEND_API_KEY", which app/env.ts does not declare`.

````ts [mail/app/env.ts]
import { defineEnv } from "hamur"

const optional = (raw: string | undefined) => raw

export default defineEnv({
  RESEND_API_KEY: { schema: optional, description: "The Resend API key; only a build that sends mail needs it" },
  WEBHOOK_SECRET: { schema: optional, description: "The secret that signs webhooks: whsec_ and the base64 of a key" },
})
````

An entry with no `schema` is **required**: the server will not start without it, `hamur dev` and tests included. You do not want that for a key that only production uses, because every developer and every test run would need a real one. The `schema` above is a function that accepts an unset variable, so the value is `undefined` where you have not set it. `hamur dev` and tests never read it, since they write to the outbox. A production server that has no key fails at its first send, and the error names the variable and says it is not set. Send one real mail after a deploy to find that out at once. If you prefer the server to refuse to start without the key, delete the `schema` line and set the variable in `.env` for `hamur dev` and in `.env.test` for tests. The same applies to every secret in this page: `SMTP_USER`, `SMTP_PASSWORD`, `POSTMARK_TOKEN` and `DKIM_PRIVATE_KEY` each need an entry. See [Environment](/environment#env-references-in-the-config).

A mail needs a body. The simplest body is a **template**: a component of your UI library in `app/mail/`. Its file name is its name.

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

Then send it from a handler. Here a visitor types their name and address on a sign-up form:

````ts [mail/server/sign-up.ts]
import { sendMail } from "@hamur/mail/server"
import { defineHandler } from "hamur/server"
import { byAddress, byIp } from "./limits.ts"
import { schema } from "./schema.ts"

const signUpInput = schema<{ name: string; email: string }>((value) => {
  const { name, email } = (value ?? {}) as { name?: unknown; email?: unknown }
  if (typeof name !== "string" || name.trim() === "" || name.length > 80 || /[\x00-\x1f\x7f]/.test(name))
    return "Enter your name"
  if (typeof email !== "string" || email.length > 254 || !/^[^\s@<>"]+@[^\s@<>"]+\.[^\s@<>"]+$/.test(email))
    return "Enter a valid email address"
  return { name: name.trim(), email: email.trim().toLowerCase() }
})

export const signUp = defineHandler({
  route: "/sign-up",
  method: "POST",
  middleware: [byIp, byAddress],
  input: signUpInput,
  async handler({ name, email }) {
    await sendMail({ to: email, subject: "Welcome to Acme", template: "Welcome", props: { name } })
    return { sent: true }
  },
})
````

`sendMail` checks the message first and throws a `TypeError` before anything is sent when it is wrong, for example `sendMail to[0] "ada@" is not an address`. When it resolves, the transport has taken the mail, and you get `{ id, queued: false }`. `id` is the `Message-ID` of the mail. Typegen reads `app/mail/`, so a wrong template name or a wrong prop fails `tsc`.

Two things in this handler keep it safe to copy:

- **The address is checked, and a limit stands in front of it.** A form that mails whatever address it is given lets anyone use your server to mail a stranger. `schema` is a small helper of the sample that refuses a bad address and a name with a control character, and `byIp` and `byAddress` are `rateLimit` steps: five requests a minute from one address of the network, three mails an hour to one mailbox. See [Sessions and security](/sessions-and-security#rate-limit) for the options.
- **The handler says nothing about accounts.** It never looks the address up, so it answers `{ sent: true }` for every address. A handler that mails only people who have an account must also answer the same for everyone else, as the [password reset](/auth#account-links-with-hamurmail) does.

````ts [mail/server/limits.ts]
import { defineMiddleware, rateLimit } from "hamur/server"

export const byIp = defineMiddleware({ server: rateLimit({ limit: 5, window: 60, key: "ip" }) })

export const byAddress = defineMiddleware({
  server: rateLimit({
    limit: 3,
    window: 3600,
    key: ({ input }) =>
      String((input as { email?: unknown } | undefined)?.email ?? "")
        .trim()
        .toLowerCase()
        .slice(0, 254),
  }),
})
````

The `schema` helper turns a check into the schema that `input` takes. Use your validation library instead if you have one:

````ts [mail/server/schema.ts]
import type { StandardSchemaV1 } from "hamur/server"

export function schema<Out>(read: (value: unknown) => Out | string): StandardSchemaV1<Out, Out> {
  return {
    "~standard": {
      version: 1,
      vendor: "docs",
      validate(value) {
        const result = read(value)
        return typeof result === "string" ? { issues: [{ message: result }] } : { value: result }
      },
    },
  }
}
````

## Read the mail while you work

Run `hamur dev` and send the form. The terminal says where the mail went: `Welcome → ada@example.com (open in devtools: http://localhost:3000/_hamur/devtools/#/mail)`.

Nothing left your computer. The mail is two files in `.hamur/mail/`, an `.eml` (the whole message, which any mail program opens) and a `.json`. The [devtools](/devtools) has a **Mail** tab that shows the same folder; see [Preview in the devtools](#preview-in-the-devtools). The folder keeps the newest 200 messages.

When the app is ready for real mail, you change nothing in the code. A build uses the transport of `$production`.

## Choose a transport

A transport is the service that delivers your mail. You need an account with one, and a domain that it has verified.

| `type`                                      | Sends through                        | Runs on                                          | Secret you set                      |
| ------------------------------------------- | ------------------------------------ | ------------------------------------------------ | ----------------------------------- |
| `resend`, `postmark`, `sendgrid`, `mailgun` | the service's web API, over HTTPS    | every preset                                     | `apiKey`, or `serverToken`          |
| `ses`                                       | Amazon SES, over HTTPS               | every preset                                     | `accessKeyId`, `secretAccessKey`    |
| `smtp`                                      | an SMTP server                       | `bun`, `node`, `vercel`, `netlify`, `cloudflare` | `password` (and often `user`)       |
| `cloudflare`                                | the `send_email` binding of a Worker | `cloudflare` only                                | none: the binding is the permission |
| `outbox`                                    | files in a folder                    | any preset that has files                        | none                                |

If you have no reason to choose, use a web API. It works on every preset, needs no open connection and answers with a clear error.

**Every secret is `env("NAME")`.** The module refuses a secret written in the config file for `password`, `apiKey`, `serverToken`, `accessKeyId` and `secretAccessKey`. Set the variable where the server runs.

### SMTP

SMTP is what a company mail server or an older service offers. `host` is required; `port` is 587, or 465 with `secure: "tls"`.

````ts [platform/mail-smtp.ts]
import mail from "@hamur/mail"
import { defineConfig, env } from "hamur"

const from = "Acme <hello@acme.example>"

export default defineConfig({
  framework: "react",
  modules: [mail],
  site: { url: "https://acme.example" },
  mail: { from },
  $development: { site: { url: "http://localhost:3000" } },
  $production: {
    mail: {
      from,
      transport: {
        type: "smtp",
        host: "smtp.postmarkapp.com",
        port: 587,
        user: env("SMTP_USER"),
        password: env("SMTP_PASSWORD"),
      },
    },
  },
})
````

On `bun` and `node` the connection stays open for up to 30 idle seconds and is used again. Elsewhere every mail opens and closes its own connection.

The certificate of the server is always checked. With `secure: "starttls"` (the default on every port but 465), a server that does not offer STARTTLS gets no password and no mail, so your credentials are never sent in clear text: `smtp.example.com:587 did not offer STARTTLS; refusing to send credentials in clear text`. `secure: false` is allowed for `localhost` only.

### A web API

The others look the same, with the key of the service. Postmark also takes the `messageStream` of the mail:

````ts [platform/mail-provider.ts]
import mail from "@hamur/mail"
import { defineConfig, env } from "hamur"

const from = "Acme <hello@acme.example>"

export default defineConfig({
  framework: "react",
  modules: [mail],
  site: { url: "https://acme.example" },
  mail: { from },
  $development: { site: { url: "http://localhost:3000" } },
  $production: {
    mail: { from, transport: { type: "postmark", serverToken: env("POSTMARK_TOKEN"), messageStream: "outbound" } },
  },
})
````

A non-2xx answer fails the send with its status and the start of the body, without the key and without addresses: `Mail "Welcome" failed on postmark: HTTP 422: …`. `tags` of a message go where the service takes them.

### Cloudflare Workers

On the `cloudflare` preset you can send through the Worker's own `send_email` binding. The binding must exist in your `wrangler.jsonc`: add `send_email: [{ name: "EMAIL" }]`, and the build checks that the name in the config is one of them.

````ts [platform/mail-cloudflare.ts]
import mail from "@hamur/mail"
import { defineConfig } from "hamur"

const from = "Acme <hello@acme.example>"

export default defineConfig({
  framework: "react",
  preset: "cloudflare",
  modules: [mail],
  site: { url: "https://acme.example" },
  mail: { from },
  $development: { site: { url: "http://localhost:3000" } },
  $production: { mail: { from, transport: { type: "cloudflare", binding: "EMAIL" } } },
})
````

The binding sends once for each recipient (`to`, `cc` and `bcc`). If it refuses the second, the first has the mail already, and the error says so in numbers, never with an address: `the message reached 1 of 3 recipients before one failed; sending it again delivers it twice to those 1`.

Workers also refuse SMTP on port 25, and the `outbox` has no folder to write to, so the build stops you at once: `mail.transport smtp on the cloudflare preset uses ports 465 or 587; Workers refuse port 25 (got 25)`.

## A template in your UI library

A template is a component of the library the app uses, in `app/mail/`. The file name starts with a capital letter: `Welcome.tsx` is the template `Welcome`. A layer can add templates, and a file of the app wins over a layer's file of the same name.

Write the template as you write any component, with these differences:

- **It renders once, on the server, with no scripts.** Nothing in it runs in the mail. A click handler, a hook that waits for the browser or a client-only component does nothing.
- **It renders outside a request.** The app's plugins do not run, the public runtime config is empty, and `useEvent()` fails. Pass everything the mail shows as props.
- **Write styles inline.** Mail programs drop a `<style>` block, so the build warns: `app/mail/Welcome.vue has a <style> block; mail clients drop it, so write styles inline`.
- **A link may be an app path.** `href="/dashboard"` becomes `https://acme.example/dashboard` from `site.url`.
- **Escape what a person typed.** Components of a UI library escape text for you. An html template is a string, so it must do it by hand.

React, Preact and Solid use the same file. The others:

````vue [vue/mail-welcome.vue]
<script setup lang="ts">
defineProps<{ name: string }>()
</script>

<template>
  <div style="font-family: system-ui, sans-serif; padding: 24px">
    <h1 style="font-size: 20px">Welcome, {{ name }}</h1>
    <p><a href="/dashboard">Open your dashboard</a></p>
  </div>
</template>
````

````svelte [svelte/mail-welcome.svelte]
<script lang="ts">
  let { name }: { name: string } = $props()
</script>

<div style="font-family: system-ui, sans-serif; padding: 24px">
  <h1 style="font-size: 20px">Welcome, {name}</h1>
  <p><a href="/dashboard">Open your dashboard</a></p>
</div>
````

````ts [angular/mail-welcome.ts]
import { Component, input } from "@angular/core"

@Component({
  template: `<div style="font-family: system-ui, sans-serif; padding: 24px">
    <h1 style="font-size: 20px">Welcome, {{ name() }}</h1>
    <p><a href="/dashboard">Open your dashboard</a></p>
  </div>`,
})
export default class Welcome {
  readonly name = input.required<string>()
}
````

An html app writes a function that returns a string, and escapes every value it puts in:

````ts [platform/mail-template-html.ts]
const escape = (text: string): string => text.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`)

export default function Welcome(props: { name: string }): string {
  return `<div style="font-family: system-ui, sans-serif; padding: 24px">
  <h1 style="font-size: 20px">Welcome, ${escape(props.name)}</h1>
  <p><a href="/dashboard">Open your dashboard</a></p>
</div>`
}
````

Without a `text`, the module writes the text part from the HTML: one line for each block, `text (url)` for a link. A mail with a text part is less likely to be taken for spam, and some people read only that part.

A mail without a template passes `html` (and, if you like, `text`) instead. A message takes a `template` or `html`, not both.

## Queue a mail

By default `sendMail` sends in the call, and its promise settles when the service has answered. That is simple and it tells the caller about a failure. It also makes the visitor wait for a mail service, and a slow service makes your page slow.

A **queue** hands the mail to a background task and answers at once. Pass `queue: true` to one call, or set `mail.queue: true` for every call:

````ts [mail/server/queued.ts]
import { sendMail } from "@hamur/mail/server"

export const queueWelcome = (email: string, name: string) =>
  sendMail({ to: email, subject: "Welcome to Acme", template: "Welcome", props: { name } }, { queue: true })
````

The call still checks the message and renders the template, so a template that fails fails the call. It then resolves to `{ id, queued: true }` when the queue has taken the mail. `delay` (whole seconds, with `queue: true`) holds it back.

Read these three limits before you turn the queue on. They are the price of the speed:

- **A queued mail can fail after the call returned.** Your handler has answered `{ sent: true }` by then. Nobody sees the failure unless you look: it is in the log, and `mail:error` runs for it. A queue that retries (below) fixes most of them; a wrong address does not get fixed.
- **A mail can arrive twice.** A queue delivers at least once, so in rare cases it runs a task twice, and the mail is sent twice. A retry after a connection was lost can do the same: the service may have taken the mail whose answer never came.
- **No retry that may deliver twice.** After a failure that leaves open whether a recipient got the mail (`the server did not confirm the message and may have accepted it`, or an HTTP 5xx other than 503) the task does not fail and does not retry. It logs `Mail "Welcome" failed on smtp: …; the queue does not send it again` at `error`. A person who reads that line decides whether to send it again.

Where the queue lives decides what survives:

````ts [platform/mail-queue.ts]
import db from "@hamur/db"
import mail from "@hamur/mail"
import { defineConfig, env } from "hamur"

const from = "Acme <hello@acme.example>"

export default defineConfig({
  framework: "react",
  preset: "bun",
  modules: [db, mail],
  site: { url: "https://acme.example" },
  mail: { from, queue: true },
  tasks: { queue: { driver: "db", maxAttempts: 5 } },
  $development: { site: { url: "http://localhost:3000" } },
  $production: { mail: { from, queue: true, transport: { type: "resend", apiKey: env("RESEND_API_KEY") } } },
})
````

- On `bun` and `node` without `tasks.queue`, the queue is this process: a mail that waits is lost when the server restarts, and nothing retries it. `tasks.queue.driver: "db"` keeps each mail as a row of your database, so a restart loses nothing and a refused mail is tried again, up to `maxAttempts` times. It needs [`@hamur/db`](/database).
- On `cloudflare` and `vercel`, `tasks.queue` names a platform queue, and its own retries apply. See [Queues and `enqueue`](/tasks#queues-and-enqueue).
- A message that waits in a Cloudflare queue may be at most 128 KB, attachments included. A larger one fails at the call. Store a large attachment as a [blob](/blob), queue a task of your own with its key, and have that task send with `queue: false`.

Use the hooks to see what happens. `mail:sent` runs after the transport took the mail, and `mail:error` after it failed. Use `mail:error` to report a failure, never to send the mail again: a queue may send it again too, and the person would get two.

## Sign your mail

Mail from a domain with no signature is easy to fake, so services that receive mail check three DNS records of your domain: **SPF** (which servers may send for you), **DKIM** (a signature on each mail) and **DMARC** (what to do with a mail that fails). Your mail service tells you which records to add, and hamur server does not change your DNS.

Every web API signs for you, and so does Amazon SES. An SMTP server that does not sign needs a signature from the app. Set `mail.dkim` and hamur server signs each mail the `smtp` transport sends:

````ts [platform/mail-dkim.ts]
import mail from "@hamur/mail"
import { defineConfig, env } from "hamur"

const from = "Acme <hello@acme.example>"

export default defineConfig({
  framework: "react",
  modules: [mail],
  site: { url: "https://acme.example" },
  mail: { from },
  $development: { site: { url: "http://localhost:3000" } },
  $production: {
    mail: {
      from,
      transport: { type: "smtp", host: "smtp.relay.example", user: env("SMTP_USER"), password: env("SMTP_PASSWORD") },
      dkim: { domain: "acme.example", selector: "mail", privateKey: env("DKIM_PRIVATE_KEY") },
    },
  },
})
````

`selector` names the DNS record `mail._domainkey.acme.example`, which holds the public key. Make the pair once:

````sh [platform/dkim-keys.sh]
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out dkim.pem
openssl pkey -in dkim.pem -pubout -outform DER | openssl base64 -A
````

The second command prints the public key. Put it in a `TXT` record at `<selector>._domainkey.<domain>` with the value `v=DKIM1; k=rsa; p=<that text>`. Set `DKIM_PRIVATE_KEY` to the whole content of `dkim.pem`, line breaks included, then delete the file. The key must be a PKCS #8 RSA key in PEM, and anyone who holds it can sign mail as your domain, so it never goes in the config or the repository. A key of another form fails the first send: `mail.dkim.privateKey must be a PKCS #8 RSA private key in PEM`. With another transport, a build warns that `mail.dkim` is read by the smtp transport only.

## Preview in the devtools

The **Mail** tab of the [devtools](/devtools#tabs) has two parts.

- **Outbox** lists what `hamur dev` wrote, newest first, with the HTML, the text part, the headers and a download of the `.eml`. The HTML opens in a frame with no scripts and no access to your page, and a content policy that allows only inline styles and images, so a mail cannot do what a page does. The list updates when a mail arrives. When the app uses another transport, the part says `The outbox is off: mail.transport is smtp`.
- **Templates** lists the templates of `app/mail/`. Choose one, type its props as JSON, and see its HTML and its text. Nothing is sent.

Use Templates while you write a template and Outbox to check the whole path, links and subject included. A mail program may show a mail in other ways than the frame does, so send a real one to yourself before launch.

## Test the mail

A test must never send mail. `hamur/test` builds the app with the `outbox` transport whatever the config says, so a test cannot reach a mail service. `sentMail` reads what was written, oldest first, and `clearSentMail` empties the folder.

````ts [mail/test/sign-up.test.ts]
import { callHandler, mockEvent } from "hamur/test"
import { clearSentMail, sentMail } from "@hamur/mail/test"
import { expect, test } from "bun:test"
import { signUp } from "../server/index.ts"

test("a sign-up sends one welcome mail to the address", async () => {
  await clearSentMail()
  const response = await callHandler(signUp, mockEvent("/sign-up", { body: { name: "Ada", email: "Ada@Example.com" } }))
  expect(response.status).toBe(200)
  const mails = await sentMail()
  expect(mails).toHaveLength(1)
  expect(mails[0]).toMatchObject({ to: ["ada@example.com"], subject: "Welcome to Acme", template: "Welcome" })
  expect(mails[0]!.html).toContain("Welcome, Ada")
  expect(mails[0]!.html).toContain('href="https://acme.example/dashboard"')
})

test("an address that is not one is refused and nothing is sent", async () => {
  await clearSentMail()
  const response = await callHandler(signUp, mockEvent("/sign-up", { body: { name: "Ada", email: "ada@" } }))
  expect(response.status).toBe(400)
  expect(await sentMail()).toEqual([])
})
````

The test calls the handler without a server, as the [testing guide](/testing#unit-tests-of-server-code) shows, and needs the [preload](/testing#the-preload) in `bunfig.toml`. A queued mail is written before `sendMail` resolves, whatever its `delay`, so a test does not wait for a queue. A test with `setup()` finds the mail of a built app the same way. Without `setup()` or the preload, `sentMail` throws and says which of the two to add.

## What to read next

[Notifications](/notifications) tell a person that something happened by mail and in other ways, and use this module for the mail. [Auth](/auth#account-links-with-hamurmail) sends sign-in, verification and password-reset links. The [`@hamur/mail` reference](/api-reference/mail) lists every option, hook and error message, and [Tasks](/tasks) explains queues.
