# Mailroom > Self-hosted mail on Amazon SES and Cloudflare Every documentation page, concatenated. Generated from https://mailroom-docs.shahriyar.dev. --- # What it is Source: https://mailroom-docs.shahriyar.dev/guide/ # What it is Mailroom is a self-hosted email platform. You run one instance, on your own server, against your own database, for your own domains. It does both halves of email: - **Sending** goes out through **Amazon SES**, so your mail arrives rather than landing in spam. - **Receiving** comes in through a **Cloudflare Email Worker**, which hands each message to your instance. Everything — messages, threads, labels, contacts, keys — lives in **your Postgres**. Attachments and raw messages live in **your R2 bucket**. Nothing passes through anybody else's service, and nothing is metered by anybody but AWS and Cloudflare. ## Who it is for One company runs one instance, and as many people work in it as you invite. The first person to sign in becomes the **owner**. After that, public sign-up is closed: everyone else arrives through an invitation, picks up a role, and sees only the mailboxes they have been granted. Teams let you grant several people at once. A stranger who finds the sign-in page cannot give themselves an inbox. It suits you if you want: - Mail on a domain you own, without paying per mailbox - Transactional sending and a real inbox in the same place - An API over both, so your own code can read and answer mail It does **not** suit you if you want a hosted product somebody else keeps running. There is nothing to sign up for. ## What it is not - **Not an SMTP server.** SES sends; Cloudflare receives. Mailroom is the application on top, not the mail transfer agent. - **Not IMAP.** There is no IMAP or POP endpoint, so Apple Mail and Thunderbird cannot connect. The web app and the API are the two ways in. - **Not a spam filter.** Cloudflare and SES do what filtering happens. Inbound mail carries its SPF, DKIM and DMARC results so you can decide for yourself. ## What you need | | Why | Cost | | --- | --- | --- | | **Postgres** | Everything is stored here | Free locally, near zero self-hosted | | **AWS** with SES | Sending | Pennies. You must ask AWS for production access, or you can only send to verified addresses | | **Cloudflare**, with your domain on it | Receiving | Free | | **Cloudflare R2** | Attachments and raw messages | Generous free tier | | Somewhere to run it | Docker anywhere: Coolify, Fly, a VPS | Your call | ## Next - [How it fits together](/guide/architecture) — what talks to what - [Self-hosting it](/guide/self-hosting) — the deploy, start to finish --- # How it fits together Source: https://mailroom-docs.shahriyar.dev/guide/architecture # How it fits together Four moving parts. Knowing which one is at fault is most of debugging a mail problem, so it is worth five minutes. ## The pieces | Piece | What it does | Where it runs | | --- | --- | --- | | **The app** | The web UI, the API, the database | Your server, in Docker | | **Amazon SES** | Hands your outbound mail to the internet | AWS | | **The inbound worker** | Catches mail for your domains, posts it to the app | Cloudflare | | **R2** | Holds attachments and raw messages | Cloudflare | Postgres holds everything else, and is the only thing you have to back up besides the R2 bucket. ## Sending ``` your code ──▶ POST /api/v1/emails ──▶ the app ──▶ SES ──▶ the internet │ └──▶ Postgres (the message, its thread) ``` SES then reports what happened to the message — delivered, bounced, complained, opened — through an **SNS topic** that posts back to the app. That is what fills in a message's `status`, and what fires the `email.*` [webhooks](/webhooks/events). Delivery reporting only works when a message was sent with a **configuration set** attached. Setting `SES_CONFIGURATION_SET` is what attaches it. ## Receiving ``` the internet ──▶ Cloudflare Email Routing ──▶ the inbound worker │ ▼ POST /api/inbound (signed) ──▶ the app │ ┌──────────┴────────┐ ▼ ▼ Postgres R2 (raw, files) ``` The worker is deployed **from the app**, under Settings → Inbound worker. You paste a Cloudflare API token once; there is no `wrangler` step of your own. Every call from the worker is signed with `INBOUND_WEBHOOK_SECRET`, so nothing else can post mail into your instance. ## Live updates The app uses Postgres `LISTEN`/`NOTIFY` with server-sent events, so a message that arrives appears in an open browser without a refresh. Nothing polls. ## Where mail is threaded An arriving message joins an existing thread if its `In-Reply-To` or `References` matches one already stored. Failing that, an identical subject in the same mailbox within thirty days joins it too. Otherwise it starts a new thread. --- # Self-hosting it Source: https://mailroom-docs.shahriyar.dev/guide/self-hosting # Self-hosting it Start to finish. Deploy **before** the SES and Cloudflare steps: both have to reach a real URL, so nothing past step 3 works against `localhost`. ## Before you start: the licence Mailroom is under [PolyForm Noncommercial 1.0.0](https://github.com/shahriyardx/mailroom/blob/main/LICENSE). Personal projects, research, teaching and charitable work are free. **Running it for a business is not**, including a company hosting its own mail on it. That needs a commercial licence — write to . The Node SDK is MIT, so your application can use it whatever you are doing. ## 0. The image **Run the published image.** Do not build from a clone — you would be compiling the same thing the release already built, and a clone follows `main`, which is whatever was merged this afternoon rather than a version somebody decided was ready. Published to GitHub's registry on every release, for `amd64` and `arm64`: ```sh docker pull ghcr.io/shahriyardx/mailroom:latest ``` Tags follow the release: `1.4.2`, `1.4`, `1`, and `latest` for the newest stable one. Pin to `1` or `1.4` if you would rather not be moved by a major version, and to an exact version if you would rather not be moved at all. Nothing about your install is inside the image. Every value below is read when the container starts, so the same image runs everybody's instance. ```sh docker run -d --name mailroom -p 3000:3000 --env-file .env \ ghcr.io/shahriyardx/mailroom:latest ``` Migrations run on boot, so there is no separate step for them and no way to forget one. Point a reverse proxy at port 3000 and carry on below. Or take the Postgres with it — `compose.yaml` in the repository runs both, and waits for the database to be ready before the app tries to migrate it: ```sh curl -O https://raw.githubusercontent.com/shahriyardx/mailroom/main/compose.yaml docker compose up -d ``` ## 1. A GitHub OAuth app — optional The first person to open the sign-in page claims the instance, either with an email and a password or with GitHub. **Skip this step** if a password is all you want: the two variables below can be left empty and the GitHub button simply will not work. Set it up if you would rather not keep another password, or if the people you invite already have GitHub accounts. **github.com → Settings → Developer settings → OAuth Apps → New** - Homepage: `https://mail.yourdomain.com` - Callback: `https://mail.yourdomain.com/api/auth/callback/github` Keep the client ID and secret. ## 2. The environment ```sh DATABASE_URL=postgres://user:pass@host:5432/mail BETTER_AUTH_SECRET= # openssl rand -base64 32 BETTER_AUTH_URL=https://mail.yourdomain.com APP_URL=https://mail.yourdomain.com GITHUB_CLIENT_ID= # both optional: leave empty to sign in by password only GITHUB_CLIENT_SECRET= AWS_REGION=us-east-1 AWS_ACCESS_KEY_ID= AWS_SECRET_ACCESS_KEY= SES_MAIL_FROM_PREFIX=mail # the return path becomes mail.yourdomain.com SES_CONFIGURATION_SET= # set to mail-events for delivery reporting (step 5) SES_SNS_TOPIC_ARN= # optional: only accept events from this topic INBOUND_WEBHOOK_SECRET= # openssl rand -hex 32 R2_ACCOUNT_ID= R2_ACCESS_KEY_ID= R2_SECRET_ACCESS_KEY= R2_BUCKET=mail-attachments UPDATE_CHECK= # set to off to stop the sidebar asking GitHub for releases ``` ::: warning BETTER_AUTH_SECRET is load-bearing It also derives the key that encrypts your stored Cloudflare token. Changing it later makes that token unreadable, and you will have to paste a new one. ::: ### Where each value comes from Three of these you generate, several you copy out of a dashboard, and two you cannot fill in until step 5 — leave those empty for the first deploy. #### You make these up | | | | --- | --- | | `BETTER_AUTH_SECRET` | Run `openssl rand -base64 32` | | `INBOUND_WEBHOOK_SECRET` | Run `openssl rand -hex 32` | | `DATABASE_URL` | Your Postgres. On Coolify, add a Postgres service and copy the internal URL it shows | #### Your app's own address | | | | --- | --- | | `BETTER_AUTH_URL` | The public URL of this app, e.g. `https://mail.yourdomain.com` | | `APP_URL` | The same URL. Both, and they must match | `APP_URL` is read when the app starts, not when the image is built, which is what lets one published image serve every install. `NEXT_PUBLIC_APP_URL` is still accepted if you already set it. #### GitHub From the OAuth app you made in step 1: | | | | --- | --- | | `GITHUB_CLIENT_ID` | On the OAuth app's page | | `GITHUB_CLIENT_SECRET` | Press **Generate a new client secret**. Shown once | #### AWS | | | | --- | --- | | `AWS_REGION` | The region you set SES up in, e.g. `us-east-1`. SES is per-region — mail sent from the wrong one fails | | `AWS_ACCESS_KEY_ID` | IAM → Users → your user → **Security credentials** → Create access key | | `AWS_SECRET_ACCESS_KEY` | Shown once, beside the key id | Give that IAM user [the policy below](#the-iam-policy). **Leave both keys empty to use an instance role instead**, which is better if you are on EC2 or anything else that can assume one. #### Cloudflare R2 In the Cloudflare dashboard, **R2 → Overview**: | | | | --- | --- | | `R2_ACCOUNT_ID` | The **Account ID** in the right-hand sidebar | | `R2_BUCKET` | The bucket you create here. Any name; `mail-attachments` is the default | | `R2_ACCESS_KEY_ID` | **Manage R2 API Tokens** → Create API token → **Object Read & Write** | | `R2_SECRET_ACCESS_KEY` | Shown once, with the key id | ::: warning Keep the bucket private Giving it a public custom domain makes every raw message and attachment readable by anyone with the URL. Let the app serve them instead — it signs short-lived links. ::: #### Filled in after step 5 These two do not exist yet. Deploy without them, press **Set up delivery reporting** on Settings → Domains, then come back. **`SES_CONFIGURATION_SET=mail-events`** — that exact string. It is what attaches a configuration set to outgoing mail, and without it SES never reports anything, so every message stays at `sent` forever. **`SES_SNS_TOPIC_ARN`** is optional, and it looks like this: ``` arn:aws:sns:us-east-1:123456789012:mail-events ^^^^^^^^^ ^^^^^^^^^^^^ ^^^^^^^^^^^ region your AWS the topic account id name ``` You cannot invent it — the middle part is your twelve-digit AWS account id. Get the real one in any of three ways: 1. **From the app.** After pressing *Set up delivery reporting*, the panel on Settings → Domains gains an **SNS topic** row. Click it to copy. 2. **From the setup script.** `pnpm ses:setup` creates the whole pipeline and writes both `SES_CONFIGURATION_SET` and `SES_SNS_TOPIC_ARN` into your `.env` for you. 3. **From AWS.** Console → SNS → Topics → `mail-events`. The ARN is at the top of the page. Setting it makes the app **refuse events from any other topic**, so a stranger who finds your `/api/ses/events` URL cannot post fake bounces at it. Worth doing once you have it; the app works without it. #### Safe to leave alone | | Default | | --- | --- | | `SES_MAIL_FROM_PREFIX` | `mail` — the return path becomes `mail.yourdomain.com` | | `SES_DKIM_SELECTOR` | `mail` — only used for keys this app generates | | `UPDATE_CHECK` | on — the sidebar asks GitHub once every six hours whether a newer release exists, and shows the version either way. `off` stops the request | | `RUN_MIGRATIONS_ON_BOOT` | `true` — set `false` to apply migrations yourself | ### The IAM policy ```json { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": [ "ses:SendEmail", "ses:GetAccount", "ses:ListEmailIdentities", "ses:GetEmailIdentity", "ses:CreateEmailIdentity", "ses:DeleteEmailIdentity", "ses:PutEmailIdentityDkimAttributes", "ses:PutEmailIdentityDkimSigningAttributes", "ses:PutEmailIdentityMailFromAttributes", "ses:CreateConfigurationSet", "ses:GetConfigurationSetEventDestinations", "ses:CreateConfigurationSetEventDestination", "ses:UpdateConfigurationSetEventDestination", "sns:CreateTopic", "sns:GetTopicAttributes", "sns:SetTopicAttributes", "sns:Subscribe", "sns:ListSubscriptionsByTopic", "sns:GetSubscriptionAttributes" ], "Resource": "*" }] } ``` ## 3. Deploy The Dockerfile builds everything, worker bundle included, and applies migrations on boot. ```sh docker build -t mailroom . docker run -p 3000:3000 --env-file .env mailroom ``` On **Coolify**: point it at your fork, build pack **Dockerfile**, port **3000**, paste the environment, deploy. ## 4. Sign in Open your URL and sign in with GitHub. That first account becomes the **owner**, and public sign-up closes behind you. Everyone after that joins through an invitation you send from **Settings → People**. Invited people set a **password**, so your colleagues do not each need a GitHub account to read their own mail. ## 5. Domains and delivery reporting See [Sending domains](/guide/domains). Short version: add each domain under **Settings → Domains**, publish the records it shows, then press **Set up delivery reporting** and set `SES_CONFIGURATION_SET=mail-events`. ## 6. Receiving See [Receiving mail](/guide/receiving). Short version: create a Cloudflare API token with six permissions, paste it under **Settings → Inbound worker**, press **Deploy worker**, then **Receive mail here** on each domain. ## 7. A mailbox **Settings → Mailboxes.** Add `you@yourdomain.com` and send yourself something. ## Upgrading Pull the tag you follow and start it again. Migrations run on boot, so there is no separate step. ```sh docker compose pull && docker compose up -d ``` Following `latest` moves you across major versions, which may need a look at the release notes first. Following `1` keeps you on that major version and takes fixes automatically, which is what most installs want. ## Working on Mailroom itself Only if you are changing the code. To *run* an instance, use the image above — it is the same build, already made, and it upgrades by pulling a tag rather than by pulling a branch. ```sh git clone https://github.com/shahriyardx/mailroom.git cd mailroom pnpm install cp .env.example .env # fill it in pnpm db:migrate pnpm dev ``` Sending works locally. Receiving does not — Cloudflare cannot reach your laptop, so deploy somewhere to test inbound mail. ## Commands For the repository, not for an install. | | | | --- | --- | | `pnpm dev` | Development server | | `pnpm build` | Bundle the worker, then build | | `pnpm db:generate` | Generate a migration from schema changes | | `pnpm db:migrate` | Apply migrations | | `pnpm db:studio` | Browse the database | | `pnpm lint` / `pnpm format` | Biome | | `pnpm typecheck` | TypeScript | | `pnpm sdk:build` / `pnpm sdk:test` | The Node SDK | | `pnpm reset-owner --yes` | Release the owner slot so another account can claim it | --- # Sending domains Source: https://mailroom-docs.shahriyar.dev/guide/domains # Sending domains **Settings → Domains.** A domain has to be verified in SES before anything can be sent from it. Mailroom creates the SES identity for you and shows the DNS to publish. ## Adding one Type the domain in and press add. The screen then lists the records — one click copies each. Publish them at your DNS host and the status moves to **verified** on its own, usually within minutes. Domains **already verified in SES** import themselves the first time you open the page. You do not have to add them again. ## What the records are for | Record | Why | | --- | --- | | Three **CNAME**s, `…_domainkey` | DKIM. Signs your mail so receivers can tell it really came from you | | **MX** and **TXT** on the mail-from subdomain | The return path, so bounces come back to SES rather than to nothing | | **TXT** SPF | Says SES is allowed to send for this domain | | **TXT** DMARC | Tells receivers what to do when a message fails the two above | SPF and DMARC are probed by Mailroom itself rather than by SES, so the ticks next to them mean "we can see it resolving in DNS". ## Subdomains are free A subdomain of a domain you have already verified needs **nothing**. Add `billing.example.com` under a verified `example.com` and it is ready immediately — SES inherits verification downwards, and Mailroom records it as covered by its parent. Such a domain shows no records of its own, because there are none to publish. ## Delivery reporting Press **Set up delivery reporting** on the same screen. It creates the SNS topic, wires SES to it, and subscribes your instance. One manual step follows: set ```sh SES_CONFIGURATION_SET=mail-events ``` in your environment and redeploy. SES only reports on a message that was sent **with a configuration set attached**, and that variable is what attaches it. Without it, every message stays at `sent` forever. Once it has run, the panel gains an **SNS topic** row showing the ARN it built — click it to copy. Put that in `SES_SNS_TOPIC_ARN` and redeploy, and the app will accept events from that topic only, so a stranger who finds your `/api/ses/events` URL cannot post fake bounces at it. `pnpm ses:setup` does the same job from the command line and writes both variables into your `.env` itself. ## The sending limit The strip at the top of the page shows your SES quota. It is a **rolling 24-hour window, not a daily allowance**. There is no reset at midnight: each message stops counting exactly 24 hours after it was sent. When you are close to the cap, Mailroom shows when the oldest message in the window ages out, which is when headroom comes back. A brand-new SES account is in the **sandbox**: 200 messages a day, and only to addresses you have verified. Ask AWS for production access before you rely on it. --- # Receiving mail Source: https://mailroom-docs.shahriyar.dev/guide/receiving # Receiving mail **Settings → Inbound worker.** Inbound mail arrives through Cloudflare Email Routing, which hands each message to a Worker, which posts it to your instance. The Worker is deployed **from the app** — there is no `wrangler` step of your own. ## The Cloudflare token Create an API token with these five permissions: ``` Account → Workers Scripts → Edit Account → Workers R2 Storage → Edit Zone → Zone → Read Zone → Zone Settings → Edit Zone → Email Routing Rules → Edit ``` That is the whole list for receiving mail. A token with exactly these five deploys the worker, turns Email Routing on, and points each domain's catch-all at it. ::: warning Zone Settings is easy to miss Cloudflare gates *turning Email Routing on* behind **Zone Settings**, not behind the Email Routing permission. Without it the deploy succeeds and receiving silently never starts. ::: ### Two more, if you want them Neither is needed to receive mail. Add either one later to the token you already have — editing a token keeps its value, so nothing has to be pasted into Mailroom again. Only a *brand new* token has a new value. | Permission | Buys you | Without it | | --- | --- | --- | | `Zone → DNS → Edit` | MX records published automatically for a subdomain of a domain already receiving here | Add that subdomain's MX records by hand | | `Account → Email Routing Addresses → Edit` | [Forwarding](/guide/forwarding) — adding and verifying the addresses a copy of your mail goes to | The Forwarding page says which permission it wants and does nothing else | **Email Routing Addresses** is an *account* permission, and a different thing from **Email Routing Rules**, the *zone* permission it sits near. Cloudflare lists them side by side and the names barely differ, which is why there is a picture: ![The Cloudflare token permission list, with Email Routing Addresses highlighted](/shots/cloudflare-token.png) Paste the token and press **Deploy worker**. The token is encrypted with a key derived from `BETTER_AUTH_SECRET` before it is stored. ## Turning a domain on Press **Receive mail here** on each domain. ::: danger This replaces the zone's MX records Turning Email Routing on for a zone points its MX at Cloudflare. Anything receiving mail on that domain today stops receiving it. Set up [forwarding](/guide/forwarding) first if you want a copy to keep reaching your old inbox. ::: ## Where mail lands An arriving message goes to the mailbox whose address it was sent to. If no mailbox matches: - A mailbox marked **catch-all** on that domain collects it. - A domain with **Capture every address** switched on creates a mailbox for the address on the spot. - Otherwise the message is dropped. ## What you get with each message Inbound mail carries the authentication results Cloudflare saw: | Field | Meaning | | --- | --- | | `spf` | Did the sending server have permission | | `dkim` | Was the signature valid | | `dmarc` | What the domain's own policy says about the two above | | `spam_score` | Cloudflare's score, when it gave one | | `mailed_by` | The envelope sender's domain — who actually handed it over | | `signed_by` | The domain in the DKIM signature, preferring the one that matches `From` | | `tls` | How the last hop reached you: `TLS1.3`, or `none` for a plaintext hop | Mailroom does not filter on these. It records them so you can, in a filter rule or in your own code. ## The raw message Every inbound message is stored byte for byte in R2. Fetch it with [`GET /api/v1/messages/:id/raw`](/api/messages#the-original-message) when you need to run it through a MIME parser, re-send it, or keep it for an audit. Outbound mail has no raw copy: it is assembled at send time and handed straight to SES. ## Filters **Settings → Filters.** Rules match on sender, recipient, subject or body, and can move a message to a folder, mark it read, star it or label it before you ever see it. They run in priority order as the message arrives. --- # Forwarding Source: https://mailroom-docs.shahriyar.dev/guide/forwarding # Forwarding **Settings → Forwarding.** A copy of inbound mail, sent on to an address outside Mailroom. Useful for keeping an old inbox fed while you move over, for an archive copy, or for getting one mailbox onto a phone that is already set up for something else. **Nothing is forwarded until you set it up.** A fresh instance forwards nowhere. It takes two steps: add the address you want mail copied to and let its owner verify it, then write a rule saying what to copy there. Neither happens on its own. ## One permission first Receiving mail needs nothing from Cloudflare's address list, so the token you made for [receiving](/guide/receiving#the-cloudflare-token) almost certainly cannot manage forwarding addresses. The page tells you so on your first visit and asks for one more permission: ``` Account → Email Routing Addresses → Edit ``` It is an *account* permission, not **Email Routing Rules**, the *zone* one of a similar name that receiving already uses. Add it to the token you already have and press **I have added it** on the page. Editing a token in Cloudflare keeps its value, so there is nothing to paste into Mailroom again — only a token created from scratch has a new value, which does have to go back on **Settings → Inbound worker**. Until then the page still shows your rules and still lets you change them, but the address list is read-only: nothing this app does can add an address Cloudflare will not let it see. ## How it decides Rules sit at one of three widths: | | | | --- | --- | | **Everything** | Every message this instance receives. | | **By domain** | Every message to any address on that domain. | | **By mailbox** | One address. | **Every rule that matches applies.** A company-wide archive copy and a copy of `support@` going to a shared phone are two rules, and a message to `support@` satisfies both, so it is copied twice. To keep something out of the wider rules, switch **Skip wider rules** on for that domain or mailbox. It only stops the widths above it — a mailbox with the switch on still follows its own rules. ::: tip Worked example `hr@acme.com` in a company that copies everything to `archive@backup.example`: switch **Skip wider rules** on for the `hr@acme.com` row, and the archive stops receiving it. Everything else still goes. ::: ## The address list is Cloudflare's A forwarding destination really lives on your Cloudflare account, so this page shows what Cloudflare holds rather than a second list to keep in step by hand. - Addresses already verified in the **Cloudflare dashboard** appear here on your next visit, already verified, with nothing to press. - Adding one here creates it there. - Removing one here deletes it there, along with every rule on this page that pointed at it. The one thing not adopted is an address on a domain this instance receives on: offering it would only offer a mail loop. ## Verifying an address Cloudflare will not forward to an address whose owner has not agreed to it. Adding one registers it with Cloudflare, which emails it a link. Until that link is clicked the address shows as **Waiting**, and a rule pointing at it does nothing at all. **Check again** asks Cloudflare what it now thinks — there is no notification when somebody clicks, so the page asks when it is opened and when you press the button. **Send again** removes the address and re-adds it, which is the only way Cloudflare offers to resend. Verification is per address and account-wide: an address verified once works for every domain on the account. An address marked **Gone** is one Cloudflare no longer has — somebody deleted the destination there. Its rules are kept rather than quietly dropped, so you can add the address again and carry on. ## How the worker knows It asks. Nothing is stored in the worker and nothing is cached in KV. For every message, the worker already posts the whole thing to `/api/inbound` on your instance — that is how mail gets stored. The reply now also carries the addresses to forward to, worked out from the rules at the moment the message arrived: ```json { "stored": 1, "forward": ["archive@backup.example"] } ``` So a rule changed on this page applies to the next message. There is no redeploy, and no window where the worker and the dashboard disagree. ::: warning Redeploy the worker once This only works with a worker built after forwarding was added. If you are upgrading, press **Deploy worker** on Settings → Inbound worker once. Until you do, the old worker ignores this page. ::: ## Mail to an address nobody owns When no mailbox claims the address, Mailroom cannot apply a mailbox rule — there is no mailbox. It falls back to the domain and instance rules, so mail to a retired address still reaches somebody instead of bouncing. If nothing matches, the message is rejected with `550 5.1.1 No such recipient here`, exactly as before. ## What is not forwarded - Mail you send. Only inbound messages. - Anything, if the address is still **Waiting**. - Anything, if no Cloudflare token is connected. ## When it stops working Forwarding happens after the message is stored, so a forwarding failure never costs you the copy in Mailroom — Cloudflare retries the whole delivery and the app ignores the duplicate. If one address stops receiving, check it still shows **Verified**. Somebody removing the destination in the Cloudflare dashboard, or unsubscribing from the link in the verification mail, takes it back to waiting. --- # Campaigns Source: https://mailroom-docs.shahriyar.dev/guide/campaigns # Campaigns **Campaigns**, the second view of the app. One message, written once, sent to everybody on a list. Switched off by default — turn **Campaigns** on in [Settings → Features](/guide/features), and a switcher appears at the top of the sidebar to move between your mail and your campaigns. An instance with **only** Campaigns on has no mail view at all, and opens straight onto the campaigns overview. ## Lists are not your contacts Mailroom already keeps a `contact` for every address it has seen mail from. That is an address book, not an audience: somebody writing to your support address once has not agreed to a newsletter. So a list is its own thing, and nobody is on one by accident. ## Consent is recorded, not assumed Every time you add addresses, you say where they came from — a signup form, an import from somewhere else, added by hand. It is stored against each person and shown next to them. This matters on the day somebody asks why you are emailing them. "We do not record that" is a bad answer, and under GDPR it is the wrong one. ## How people get on a list Four ways, and each records where the person came from. | | | | --- | --- | | **By hand** | Paste addresses into the Add people dialog | | **A CSV** | Drop a file on the same dialog | | **Your own signup form** | `POST /api/v1/lists/:id/members` from your site's backend | | **Someone else's system** | The same call, from whatever already knows about your users | ### The subscribe API ```sh curl -X POST https://your-instance/api/v1/lists/lst_123/members \ -H "Authorization: Bearer mk_live_..." \ -H "Content-Type: application/json" \ -d '{"address":"ada@example.com","name":"Ada","consent_source":"footer signup form"}' ``` `consent_source` is **required**. It is the answer to "why am I getting this", and a field you cannot forget to fill in is worth more than a field you can. The reply says what happened to that person, because a signup form has to show them something: | `status` | Meaning | | --- | --- | | `subscribed` | New, and now on the list | | `already` | They were already subscribed; nothing changed | | `resubscribed` | They had left and have now signed up again | A `409` means the address hard-bounced or reported a previous message. It is **not** resubscribed by a form submission — the address is broken or its owner reported you, and writing there again costs the deliverability of everybody else on the list. The key needs the `lists:write` scope. `DELETE` on the same path with `{"address":"…"}` takes somebody off, and `GET /api/v1/lists` lists your lists. ::: warning The API needs a key Every call to `/api/v1/lists` needs one, so a form on your website posts to **your own backend**, which then calls this. There is also a **hosted signup page** with no key and no account — see below. It is off for every list until you switch it on, because a keyless endpoint anybody can find will be filled with junk addresses within a week, and junk addresses are what get a sender blocked. ::: ### The hosted signup page Open a list and turn on **Give this list a signup page**. The address shown next to the switch is a plain page anybody can open: ``` https://your-instance/subscribe/lst_123 ``` It is plain HTML that posts to itself — no JavaScript, so it works wherever you link it from. Off, that address returns a 404 rather than an explanation: confirming which list ids exist to anybody who guesses is not information worth handing out. None of its answers say whether the address was already on the list. "You are already subscribed" on a public form is a way to find out who is on it, one guess at a time. ### Putting the form on your own site The same page, in an iframe. Turn the signup page on and the snippet is under the switch, ready to paste: ```html ``` `?embed=1` drops the card, the centring and the background, so it takes the styling of the page around it instead of looking like a window onto somewhere else. An iframe rather than a form you paste and point at us. A pasted form sends the reader away from the page they were on to see "you are subscribed" on your instance; the frame answers where it stands. It also keeps working when the form changes. ::: tip It needs no JavaScript The frame is a plain HTML form that posts to itself, so it works behind a content blocker and on a static site. ::: ### Double opt-in Turn on **Make people confirm by email** and a new signup lands as `pending` instead of `subscribed`. They are sent one email with a link, and until they click it they are in no audience and get nothing. It costs you roughly half your signups. It is worth it: a form without it is a way for a stranger to sign somebody else up, and that person reports your next campaign as spam — which is counted against every other message from your domain. The confirmation link works twice. Mail providers run link scanners that follow every URL in a message before the reader sees it, so the second visit is usually not even a person. ## Segments A segment is a **question about a list**, not a copy of one. | It can ask about | Examples | | --- | --- | | Engagement | Opened nothing in the last 30 days; clicked a campaign | | Their details | Address contains, name is set, joined after a date | | Status | Subscribed, not confirmed, unsubscribed, bounced | | Tags | Has `vip`; does not have `customer` | | Merge fields | `plan is pro`, `city contains London` | The rules are stored and run **at send time**, never before. A stored list of members goes quietly stale — somebody who unsubscribed on Tuesday is still in Monday's copy of it, and they get mailed. The builder counts how many people match as you type, because a segment is a question and the only way to know it is the right one is the answer. A campaign aimed at a segment that matches nobody is **refused with a reason** rather than sent to nobody. Segments live on the page of the list they are about, under **Segments of this list** — which is where you are when you think of one, and where the people they describe already are. ::: tip A segment about status is for looking, not sending Mail only ever goes to people who are subscribed. A segment of unconfirmed people is useful for seeing how many are stuck there; a campaign aimed at one is refused rather than sent. The count for such a segment includes them, or it would answer "0" to "who has not confirmed yet" and look like a broken rule. ::: Tags are put on people by an [automation](/guide/automations) — an **Add or remove a tag** box — and shown beside each person on the list's own page. ## Testing two subject lines Fill in **Subject B** in the campaign panel. That is the whole switch — there is nothing else to turn on. The audience is split in half by a stable hash of the recipient, so both sides are the same size and the same person always lands on the same side. The campaign's report shows the open rate for each. ::: tip A difference of a point or two is noise On a list of a few hundred, an A/B result only means something when it is large. Two subject lines that land within a few points of each other have told you they are equally good. ::: ## Sending it again to the people who never opened it On a finished campaign's report, **Send again to non-openers** makes a new draft aimed at exactly the people who were sent the original and never opened it. Its audience comes from that campaign's own recipients rather than from the list, because somebody who joined afterwards was never sent the first one, and a reminder about an email you never received is nonsense. It is a **draft**, not a send. The point is to change the subject line — sending the identical email to the same inbox twice is how you teach a mailbox provider to filter you. ### Uploading a file Drop a CSV on the **Add people** dialog, or pick one. It is read in your browser and its contents put in the box, so you can see what you are about to add before anything is written. Three shapes are understood: | The file | What happens | | --- | --- | | One address per line | Each becomes a person with no name | | `ada@example.com, Ada Lovelace` | The part after the comma becomes the name | | A CSV with a header row | Columns named `email` and `name` are found wherever they sit | Quoted fields are handled, so `"Lovelace, Ada",ada@example.com` is a name and an address rather than three broken columns — which is what every export from every other tool looks like. Any **other** column in a file with a header is kept as a merge field, so an export carrying a plan or a city can be used in a subject line without reshaping the file first. ### Taking them back out **Export** on a list's page downloads everybody on it as a CSV — addresses, names, status, tags, where the consent came from and when, and one column per merge field. The download icon beside a segment exports only the people that segment describes. It is the same shape the importer reads, so a file exported here goes straight back in, here or anywhere else. A tool that imports and does not export is one you should think twice about putting a list into. ::: tip Re-importing is safe Somebody already on the list is left exactly as they are. Importing last month's file again will **not** resubscribe anybody who has left since — which is the most common way a sender ends up in a spam folder, and it is always an accident. ::: ## Writing a broadcast A broadcast is saved as a **draft** first. Sending is a separate press, because it is the one thing here that cannot be taken back. Anything in double braces is filled in per person, in the subject and in the body: | | | | --- | --- | | {{name}} | Their name, or **there** if you have none | | {{address}} | Their email address | | {{plan}}, {{city}}, … | Any merge field they carry | | {{unsubscribe}} | The link that takes them off this list | Merge fields are whatever an import, an API call or an automation's **Set a field** box put on somebody. The builder lists the ones the people on this list actually have, next to the subject — click one to copy it. Capitalisation and spacing do not matter: a column headed `Plan Name` is reached by {{plan name}}, {{plan_name}} or {{planname}}. An export's header is not something anybody should have to reproduce exactly in a subject line. ### When somebody does not have it Say what to use instead after a `|`: ``` Your {{plan|free}} plan renews on the {{renews|1st}} ``` With no fallback, a field nobody has becomes **nothing** — the sentence closes up around it. What it never does is reach the reader as `{{plan}}`, which is the one outcome that cannot be explained away. ::: tip Send yourself a test first A fallback is only ever exercised by the people who are missing the field, and they are the ones you are not looking at while you write. ::: Values are escaped on their way into an HTML body, so a city of `London` arrives as text rather than as markup. They came from a spreadsheet somebody else exported; they are not trusted to be HTML. Leave {{unsubscribe}} out and a plain one is added at the bottom. There is no way to send without it, and that is deliberate. ### View in browser Put {{view_in_browser}} in a campaign and it becomes a link to a web copy of that message. It is also on the campaign's report, as **Web copy**, for putting a newsletter somewhere that is not an inbox. The page needs no sign-in — somebody whose mail client mangled your layout is by definition not a user of your instance. Its link is signed rather than stored, so one dug out of a year-old email still works, and it is marked `noindex`: a campaign is not a page anybody asked to publish. The link carries the **campaign**, not the reader. It is the link in an email most likely to be forwarded, and one that identified the person it was sent to would hand their row to whoever it reached. So the web copy is not personalised — a greeting reads "Hi there". A draft has no web copy. A link that worked before a campaign was sent would be a way to read one early. ## The report A campaign that has started opens as its report rather than in the builder. What went out is what went out, and an editor over it would be offering to change history. | | | | --- | --- | | Sent, failed, skipped | What happened to each copy | | Opened, clicked | People, not events — a newsletter forwarded round an office is one reader | | Unsubscribed | Who this campaign cost you | | Bounced, complained | Fed back from SES, often hours later | | Links | How many **people** followed each one | Every rate is over the number **sent**, not the number delivered. Sent is the number you pressed a button for; dividing by delivered is the flattering version most tools quietly use. ::: warning Clicks need switching on in SES Link tracking is done by SES rewriting the links in your message, which it only does when the configuration set says to. Without it the Links panel stays empty — Mailroom never sees a click. Nothing here is a redirect of our own, deliberately. A tracking domain has to answer forever or every link in every email you have ever sent breaks. ::: ## How it is sent Each copy goes out through the same path the composer and the API use, one recipient at a time, a small batch every few seconds. That is slower than handing the whole list to SES at once, and it buys things a bulk send has none of: every copy gets a row in the email log, bounces and complaints come back per person, and an address that hard-bounces is suppressed automatically. A send that is interrupted — a restart, a crash — picks up where it stopped. Everybody not yet sent to is still marked pending, and nothing is sent twice. ::: warning The audience is frozen when you press Send Who it goes to is decided at that moment, so what went out can be explained afterwards. Somebody subscribing mid-send is not included. Somebody who **unsubscribes** mid-send is still dropped. Each recipient is checked again as their copy goes out. ::: ## Unsubscribing Every broadcast carries a `List-Unsubscribe` header and the one-click form of it (RFC 8058). This is not a courtesy — **Gmail and Yahoo refuse bulk mail without it.** The link needs no sign-in. Somebody unsubscribing is, by definition, not a user of your instance, and asking them to log in to stop receiving mail is how a complaint becomes a spam report. Unsubscribing is **per list**. Leaving the newsletter does not stop the release notes they also asked for, and it never blocks a message somebody sends them directly. The link is signed rather than stored, so one dug out of a year-old email still works. ## Choosing what you get Put {{preferences}} in a campaign or an automation and it becomes a link to a page of switches — one per list that address is already on. It is also offered on the unsubscribe page, **after** they have left, never instead of leaving. That ordering is the whole point. Making somebody manage preferences in order to unsubscribe is the trick that produces spam reports, and a spam report costs you the deliverability of everybody else on the list. They are off the list before the page loads; the other lists are something they may now want to look at. Clearing every box stops all of it, so "unsubscribe from everything" needs no button of its own. ::: warning It can never add somebody to a list Only lists that address is already known to are shown. A preference centre that offered new ones would be a signup form wearing a different hat, and this page is reached from a link rather than from a decision to join anything. An address that hard-bounced or reported you is shown but locked. A spam report is not a preference, and a forwarded link must not be able to undo one. ::: ## Your postal address Set it in **Settings → Company**. It is printed at the foot of every campaign and every automation. This is not decoration. US CAN-SPAM requires a valid physical postal address in commercial email, and Gmail's bulk sender rules lean on the same thing. Campaigns still send without one — Mailroom is not the right place to block your work — but every campaign screen will keep saying so until it is filled in. ## Keep marketing away from your real mail Sending campaigns from the same domain your team's mail comes from puts one reputation behind both. A bad campaign then costs you your password resets and your replies to customers. Send broadcasts from their own domain, or at least their own subdomain. It is the single most valuable thing on this page. ## Slowing it down on purpose **Settings → Company → Send no more than** sets a ceiling on how much bulk mail leaves this instance in an hour. Empty means no ceiling, which is the default. The reason to set one is **warming a new sending domain**. A domain that goes from nothing to tens of thousands of messages in an afternoon is read by every provider as a compromised account, and the reputation that costs takes weeks to earn back. A few hundred a day for a week, then a few thousand, is the boring cure — and it is not something anybody can follow by watching a progress bar. It counts campaigns and automations **together**, over a rolling hour. A cap covering only one of them would be a cap you trusted while the other quietly spent it, which is worse than no cap at all. Nothing is dropped when the ceiling is reached. A campaign stays as it is, with everybody unsent still pending, and carries on in the hours after — the same way it survives a restart. ## Limits worth knowing | | | | --- | --- | | Amazon SES | Rate limits per second and a daily quota; new accounts start small | | Cloudflare Email Routing | 200 verified destination addresses per account | Mailroom paces sending to stay under the SES rate rather than burning retries on the first minute of a large send. --- # Automations Source: https://mailroom-docs.shahriyar.dev/guide/automations # Automations A campaign goes to everybody at once. An **automation** starts when one person does something, so its third email lands three days after *their* signup — whenever that was. Find it under **Campaigns → Automations**. ## What starts one A new automation is an empty canvas with one thing on it: **Start with a trigger**. There are two. | Trigger | Starts when | | --- | --- | | **Somebody joins a list** | They subscribe — by hand, by import, through the API, or through the signup page | | **An event you post** | Your own code calls the API to say something happened to somebody | The first covers a welcome series. The second covers everything else a product wants to say, because only the product knows it happened: a trial ending, an order shipping, a card being declined. Both kinds can name a list. For a joining trigger it is the list to watch; for an event it is where those people live, which is what unsubscribe links and merge fields are read from. Leave the list empty and it means **any list**: | Trigger | With no list | | --- | --- | | **Somebody joins a list** | Anybody who joins any list. Once per person — joining a second list does not start it again | | **An event you post** | The person can be on any list. Somebody on no list is skipped, and `consent_source` cannot add them, because there is no list to add them to | The list they joined — or, for an event, the one they joined most recently — is where their unsubscribe link and merge fields come from. Segments belong to one list, so they are only offered once a list is picked. Only somebody who can send to every list can switch on a flow with no list. Either kind can be narrowed to a **segment** — *only if they match* on the trigger card. The rules are asked at the moment somebody would be put in, so a flow for "people on the pro plan" is right on the day it runs rather than on the day the segment was written. An event for somebody outside the segment comes back `skipped`, naming the segment. ::: warning You cannot switch one on until the trigger is answered A half-answered trigger — an event flow with no event — leaves the **Switch on** button disabled and the trigger card marked in amber. It is the one thing that cannot be discovered later, because "nothing happened" looks the same either way. ::: ## Events An event is a name your own code posts, listed under **Campaigns → Events**. Declare one there, or simply post it — an event arriving under a name nobody declared is recorded anyway, marked **Not declared**, because that is the answer to "why did my flow not run" and it can only be given if it was kept. Names are lowercased and tidied on the way in, so `Trial.Ended` and `trial.ended` are the same event. ```bash curl -X POST https://mail.example.com/api/v1/events \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "event": "trial.ended", "email": "person@example.com", "fields": { "plan": "pro" }, "consent_source": "signed up at checkout" }' ``` The key needs the **Events** scope. What comes back names every automation that heard it and what happened to that person in each: ```json { "event": "trial.ended", "declared": true, "matched": 1, "automations": [ { "id": "aut_…", "name": "After the trial", "status": "started" } ] } ``` | Status | Meaning | | --- | --- | | `started` | They are at the top of the flow | | `restarted` | They had finished it before; they are back at the top | | `already_running` | They are part-way through it, so nothing was done | | `skipped` | Nothing happened, and `reason` says why | `fields` are merged onto the person before the flow starts, so the first email can say the order number and the first condition can read the plan. Merged, not replaced — an event about one thing does not wipe what is known about everything else. ::: tip consent_source is what adds somebody An address nobody on the list has heard of is **skipped**, not added. An event carrying an email is not that person asking for mail. Send `consent_source` with it — the same field the subscribe endpoint requires — and they are added first, and the flow starts. On a double opt-in list they are added as *pending* and the flow waits: they have to confirm first, which is the whole point of that setting. ::: Unlike a joining trigger, an event can fire for the same person again and again. A finished run starts over; a run still going is left alone rather than doubled up. ## The canvas An automation is a flow drawn top to bottom: a trigger, then boxes, with conditions branching into a **yes** side and a **no** side. | Box | What it does | | --- | --- | | **Send an email** | Written in the same builder templates and campaigns use | | **Call a webhook** | Tells your own server that somebody got here | | **Wait** | Holds somebody here — for a length of time, or until a date | | **Split on a condition** | Two ways on — one for yes, one for no | | **Wait for an event** | One way if the event arrives in time, the other if it does not | | **Split at random** | Sends a share of people each way, to test two versions | | **Set a field** | Writes something onto the person that a later condition or a segment can ask about | | **Add or remove a tag** | Puts a label on them, or takes one off | | **Copy or move to another list** | Puts them on a second list, with or without leaving this one | | **Take them off the list** | Ends their journey here | Nothing is dragged. Every arrow carries a **+**, empty branches included, and whatever that arrow pointed at becomes the new box's own next — so inserting in the middle never leaves anything unattached, and removing a box joins the flow back up around the gap instead of severing everything below it. ::: tip Why you cannot move the boxes The picture is worked out from the shape of the flow, not stored. Saved positions drift: somebody drags a box, somebody else inserts one above it, and the arrows cross. Laid out automatically the picture is always readable and there is nothing to keep tidy. The price is one rule — **branches never rejoin**. A box has one box before it, which is what makes the flow a tree and a tree is what can be laid out. ::: Click any box to open its settings beside the canvas. Drag the background to move around, and use the zoom control in the corner for a flow that has outgrown the window. ## Waiting for a while, or waiting for a date A **Wait** box does one of two things, and the difference matters. | | | | --- | --- | | **For a while** | Counted from the moment *that person* reaches the box. A hundred people reach the next box at a hundred different times | | **Until a date** | The same instant for everybody waiting there | Use the second one for anything with a date attached — a launch, a webinar, an announcement. Somebody who joined in March and somebody who joined an hour before all move on together at the moment you set. Anybody who reaches the box *after* that moment has passed walks straight through. Holding them until the same date next year is the only other option, and nobody means that. If you change how long a wait is, the people already sitting on it follow the new length too. It is counted from when each of them arrived. ## Waiting for an event A **Wait for an event** box holds somebody until one of two things happens: | | | | --- | --- | | **Arrived** | Your code posts the event for them while they are on the box. They go down this side at once | | **Timed out** | The time you set runs out first. They go down this side | This is what a cart-recovery flow is built on: wait up to a day for `order.placed`, thank the ones who bought, and nudge the ones who did not. Only an event that arrives *while they are on the box* counts. One that came before they got there is not saved up for them. ## Testing two versions **Split at random** sends each person one way or the other by chance. You set the share — 50/50, or 90/10 to try something new on a few people first. Put a different email on each side. The numbers on each email box then tell you which version gets more opens and clicks. ## Calling your own server **Call a webhook** sends a `POST` to a URL you choose, with the person's email, name, fields and tags as JSON: ```json { "event": "automation.step", "automation": { "id": "aut_…", "name": "Welcome" }, "step": "atn_…", "person": { "email": "person@example.com", "name": "Ada", "fields": {}, "tags": [] }, "at": "2026-09-26T10:00:00.000Z" } ``` It is signed in the `X-Mailroom-Signature` header, the same way as your account's [webhooks](/webhooks/). Each automation has its own signing secret, shown on the box. The URL must be `https` and a public address. An answer that is not `2xx` counts as a failure and is tried again, the same as an email that fails. ## Tags, and other lists **Add or remove a tag** puts a label on somebody: `customer`, `vip`, `webinar-march`. A tag is a set they are in or out of, so adding one twice does nothing and removing one they never had is not an error. Tags show on the list's own page, a [segment](/guide/campaigns#segments) can ask about them, and so can a condition further down the same flow. **Copy or move to another list** does what it says, and the difference is what happens here: | | | | --- | --- | | **Copy** | They go on the other list *and* stay on this one, carrying their name, fields and tags. The flow carries on | | **Move** | They go on the other list and come off this one. This flow follows this list, so their journey here ends at that box | Moving marks them off the list rather than deleting them, so everything ever sent to them is still in the reports. If the other list asks people to confirm by email, they arrive there as *not confirmed* and are sent the confirmation — being copied is not a way around that setting. ## Letting people out early A flow is usually trying to make something happen — a purchase, an upgrade, a booking — and the worst thing it can do is keep writing to somebody after they have already done it. **Stop early when**, on the trigger card, says when to let them out. Two ways, and both can be set: | | | | --- | --- | | **They match a segment** | Checked before every step. Tag somebody `customer` when they buy, and a flow watching that segment drops them at the next step rather than at the end | | **An event arrives** | Checked the moment it lands. `order.placed` ends the cart-recovery flow that second, not two days later at the next email | The run is marked **stopped** with the reason, so the record of how far they got survives. ## What can be asked A condition asks one of three things: | | | | --- | --- | | **They opened the last email** | The last one **this flow** sent them | | **They clicked the last email** | Same, for clicks — needs click tracking on in SES | | **A tag on them** | Whether they carry `customer`, `vip`, and so on | | **A field on them** | `plan is pro`, `city contains London`, `stage is empty` | | **Whether they match a segment** | Anything the segment language can ask, as one question | | **Whether they are on another list** | Asked by email address, counting only people still subscribed there | A condition placed before the flow has sent anything takes the **no** branch: they were never written to, so they did not open it. **Whether they match a segment** is the one worth knowing about: it borrows the whole rule language rather than growing a second one here, so a condition can ask "opened nothing in the last thirty days", "joined before March", "has the tag `vip`" or any combination, without any of that being rebuilt on the canvas. The fields are the same ones a [segment](/guide/campaigns#segments) uses, and the same ones a CSV import brings in. A **Set a field** box earlier in the flow is how you mark where somebody got to. ## Who gets put through it On a **joining** trigger, only people who **join after you switch it on**. Switching on a welcome series must not send a welcome to ten thousand people who have been subscribers for two years, so enrolment starts from the moment the automation was created. Everybody who joins the list from then on is put in, however they joined — by hand, by import, through the API, or through the signup page. On a double opt-in list that means when they *confirm*, not when they ask. | What happens | Result | | --- | --- | | They unsubscribe part-way through | They stop where they are; nothing more is sent | | You pause the automation | Sending stops, nobody loses their place, and it resumes on unpause | | You delete a box they are sitting on | They move on to the next one | | You delete the whole automation | Everybody in it stops. Mail already sent is unaffected | Somebody can only be in an automation once at a time. Re-subscribing does not start a second copy of the welcome series while the first is still running, and neither does a second event while the first run is going. ## How each email did Every email an automation sends is recorded, so each box carries its own numbers — **sent**, **opened**, **clicked** — on the card and in its pane. That is the sentence worth reading on this screen: the second email gets half the opens of the first, and the third barely any. Opens are the tracking pixel and mean "it was loaded", not "it was read". Clicks need click tracking switched on in SES. ## Only sending at set hours On the trigger card, **Only send email between** sets the hours and days email may go out, in a time zone you choose. For example, 9:00 to 17:00, Monday to Friday, in `Europe/London`. Somebody who reaches an email outside those hours waits there until the window opens. Everything else in the flow — waits, conditions, tags — still runs straight away, because none of it lands in an inbox. A window that starts later than it ends, such as 22:00 to 06:00, runs over midnight. ## Who is in it Every box with people on it carries a small count in its corner. Click it to see who they are. **People**, at the top right of the canvas, lists everybody the flow has put through it: - where each person is now, and until when - what the flow sent them, and whether they opened or clicked it - why anybody stopped: they left the list, they reached the goal, an email kept failing You can take one person out of the flow from there. They stay on the list, and they are not put back in if they join again. ## A test run **Test run**, at the top right of the canvas, walks one person through the flow on paper. Type an address, and the path they would take lights up on the canvas, with each step written out beside it. Nothing is sent, written or called. Their real fields, tags and segments answer the questions they can. You answer the rest: whether they open the emails, whether the events they wait for arrive, and which way a random split sends them. ## Copying one The copy button on an automation's row, or beside **Switch on**, makes a copy of the whole canvas. The copy starts as a draft with nobody in it, so it sends nothing until you switch it on. ## Warnings on the canvas A box turns amber when it will run but not do what you meant: - an email with nothing written in it - **Opened the last email?** straight after the email, with no **Wait** in between — nobody has had time to open it, so the answer is always no - **Opened the last email?** with no email before it at all - a **Wait for an event** with no event, or a webhook with no URL ## The clock A run is a row with a box and a date on it. There is no timer per person, so a flow with a fortnight's wait in the middle costs the same as one with no wait at all. Boxes that take no time — a condition, a field write — are walked straight through, so a person does not spend thirty seconds sitting on each one. An email or webhook that fails is tried again rather than dropped: after 15 minutes, then 1 hour, 4 hours and 12 hours. Almost everything that fails is temporary, and abandoning the second email of a welcome series over a blip is worse than being late. After the fifth failure the person is stopped, with the error as the reason, so a broken address does not retry forever. A busy flow is not held back by a fixed batch size. Each pass keeps going until nobody is due, so an import of thousands onto a welcome list starts straight away. The [hourly sending limit](/guide/campaigns#slowing-it-down-on-purpose) still applies. ## Before you switch it on - Every email box needs a body. An empty one is flagged on the canvas, and an empty email still goes out — blank. - Your [postal address](/guide/campaigns#your-postal-address) is printed at the foot of every one of these, the same as a campaign. - It starts as a **draft** and sends nothing until you press **Switch on**. --- # Metrics Source: https://mailroom-docs.shahriyar.dev/guide/metrics # Metrics **Settings → Metrics**, or **Metrics** in the campaigns view. The same screen either way. The email log answers *what happened to this message*. This answers the other half: whether the account as a whole is healthy. A bounce rate means nothing on its own — it means something against the volume it sits on and the direction it is moving in. ## What is on it | | | | --- | --- | | **Emails** | Everything sent in the window, one bar per day. Bounces sit on top of each bar rather than beside it: they are part of what was sent, not a second thing that happened. | | **Delivered** | Of everything sent. | | **Opened** | Of everything *delivered*. A message that bounced was never going to be opened. | | **Bounce rate** | Mail SES could not deliver, split by the type it gave. | | **Complaint rate** | People who pressed the spam button. | Filter by domain and by how far back to look: 7, 15, 30 or 90 days. Both live in the URL, so a view is a link you can send somebody. ## The two lines you must not cross The dashed red line on each chart is Amazon's, not ours. | | Under review | Suspended | | --- | --- | --- | | Bounce rate | 5% | above it | | Complaint rate | 0.1% | above it | That is why the rates carry two decimals. A complaint rate rounded to whole percent reads 0% right up to the point the account is suspended. ::: tip A rising bounce rate is usually a list, not a server Permanent bounces mean addresses that do not exist — an old list, or one bought rather than collected. Transient means a full mailbox or a server having a bad day, and fixes itself. The split on the card tells you which you have. ::: ## What is counted - Outbound mail only. Receiving has no delivery to rate. - Drafts are not counted. Nothing has been attempted. - [Test sends](/guide/test-mode) are left out everywhere. They never reach SES, so counting them would make every rate here a rate of something that did not happen. - A complaint counts as delivered as well. It could not exist otherwise, and a deliverability rate that falls when somebody presses the spam button is measuring the wrong thing. - Days are bucketed in UTC, and every day in the range gets a bar — including the ones nothing went out on. ## Where the numbers come from Straight out of the message table and the SES events written against it, in one pass, every time the page is opened. There is no nightly rollup and no summary table: an instance that has to summarise its own mail before it can draw a chart is an instance with a second set of numbers to keep in step. Bounce and complaint figures need [delivery reporting](/guide/domains) connected — without the SES event feed nothing ever tells this instance that a message bounced, and the rate stays at zero while the bounces pile up. --- # Templates and media Source: https://mailroom-docs.shahriyar.dev/guide/templates # Templates **Settings → Templates**, or **Templates** in the campaigns view. The same screen either way. A template is a subject and a body you save once and send by its id. Your code passes the id and the values that go in the holes; the words, the layout and the colours stay here, where somebody can change them without a deploy. ## The builder A template opens on a page of its own, with the app's navigation out of the way: a palette on the left, the email in the middle, and everything about the selected block on the right. The arrow at the top left is the way back. The palette has two halves. **Blocks** are the parts. **Sections** are ready- made arrangements — a hero, a picture beside some words, three features across, a row of numbers — dropped in one press. A section is made of ordinary blocks, so everything in it can be moved, restyled or deleted afterwards. Click a block in the palette to put it at the end, or drag it to land it between two others. Drag a block already on the canvas to move it. Headings, text, quotes and table cells are typed where they sit rather than in the side panel. | Block | For | | --- | --- | | Heading | Three sizes: title, heading, subheading. | | Text | Paragraphs, with bold, italic, links and lists. | | List | Bulleted or numbered, drawn so Outlook cannot re-indent it. | | Callout | A boxed notice, with a stripe and an optional emoji. | | Quote | An indented line with a coloured bar. | | Code | A monospaced block. | | Image | From the media library, or any address. | | Gallery | Two, three or four pictures across. | | YouTube | The video's thumbnail, linked to it. | | Button | A real one that Outlook draws properly. | | Menu bar | A row of text links across the top. | | Numbers | Big figures with a word under each. | | Columns | Two to four, side by side, stacking on a phone. | | Table | Bordered, with an optional heading row. | | Divider, Spacer | Room and lines. | | Social links | A row of links. | | Unsubscribe | The footer a broadcast needs. | | Raw HTML | For whatever none of the above covers. | ::: tip Why there is no chart, barcode or video block Every one of those needs either JavaScript or a live picture, and an email client gives you neither — so they arrive as a flat image, which most readers never agree to load. A number written as text is read by everybody. ::: Every block carries its own colour, size, line height, letter spacing, weight, padding, background and border, under **Typography**, **Spacing** and **Background & border**. The **Page** tab holds the things that apply to the whole email: the page colour behind the card, the card itself, the width, the font, and the text and link colours. `Ctrl`+`Z` takes back the last change and `Ctrl`+`Shift`+`Z` puts it back, or use the two arrows in the bar. A field you are typing in keeps its own undo, so the shortcut takes back the sentence rather than the block it is in. ### The preheader **Page → Inbox** holds the grey line an inbox prints after the subject. Leave it empty and the client picks the first words of the email instead, which is how "View this email in your browser" becomes the summary of a newsletter. Around 80 characters is what most clients show. ### Leaving a block off one screen **Visibility → Show on**, on any block: *Everything*, *Desktop only*, or *Phone only*. A media query does the hiding. Outlook has none, so it shows whatever a desktop would have seen — which is the right way round, but it does mean a phone-only block is not a way to keep something out of Outlook. Use it for a wide picture a phone has no room for, never for anything the message needs to make sense. ### Duplicating one The copy button on a row in the template list makes a second template with the same body under a free name — `welcome` becomes `welcome-copy` — and opens it. The original keeps sending exactly as it did. ## Variables Anything in double braces is filled in when you send. ``` Hi {{ name }}, your order {{ order.id }} is on its way. ``` {{ name }} escapes what it puts in, so a value arriving from a form cannot write tags into mail going out under your domain. {{{ name }}} does not, for a value that is already markup. A dot reaches into an object. A missing value is an error rather than an empty string: `Hi ,` going to a customer is worse than a 422 telling the caller what it forgot. The **Details** tab lists every variable the template currently asks for. ## Test send **Test send** in the bar mails the template to one address through the ordinary send path — the same code a real send uses, so an unverified domain or a refused address is refused here rather than in front of a list. Variables are filled with their own names in brackets, so you can see where they land. The preview beside it is a browser drawing HTML written for mail clients, which is the one thing it cannot tell you about. Send yourself a copy before a list gets it. **Preview** offers three switches: - **Desktop** and **Phone** change the width. The phone frame is narrow enough that the email's own rules for a small screen apply — columns stack, and anything set to desktop only disappears. - **Dark client** shows what a client that forces dark mode does: it inverts the colours and leaves the pictures alone. This is where a dark logo on a dark background turns up before a customer finds it. ## HTML The **HTML** tab shows what the builder compiles to. It is read-only and rewritten on every change, with a button to copy it — an editable copy of generated output is a promise the builder cannot keep, because the next click on the canvas overwrites it. Nothing reads arbitrary email HTML back into blocks, so the two doors between the builder and hand-written HTML are both one-way and both labelled: - **Take it over** copies the compiled HTML into an editor and leaves the builder behind. - **Build it instead**, on a hand-written template, starts a fresh canvas and replaces the HTML the next time you save. A template created through the API carries HTML and no blocks, so it opens hand-written. ## Media **Settings → Media** holds pictures your mail can point at. Upload a file and it gets an address anybody can fetch — which is the point: an image in an email is fetched by whoever opens the message, days later, from a machine that has never heard of your instance. The address is unguessable and it is the whole of the secret, the same bargain every hosted image has. Removing a file takes it out of the library and leaves the bytes where they are, so mail already sent does not fill up with broken images. PNG, JPEG, GIF, WebP and PDF, up to 10 MB each. ## Sending one ```ts await mailroom.emails.send({ from: "hello@yourdomain.com", to: "customer@example.com", template: "tpl_…", data: { name: "Sam", order: { id: "A-1183" } }, }); ``` The id is what your code passes. Find it in the template's Details tab, or next to its name in the list. It never changes, so you can rename a template at any time. ::: warning Deleting a template breaks the code that used it Anything still sending by its id gets a 404. Mail already sent is unaffected: the body was copied into the message when it went. ::: --- # Features Source: https://mailroom-docs.shahriyar.dev/guide/features # Features **Settings → Features.** Two products share this app, and an instance says which of them it is: | | | | --- | --- | | **Inbox** | Mailboxes, conversations, filters, labels, forwarding, the browser extension | | **Campaigns** | Lists, broadcasts, unsubscribe handling | **Both can be on.** A company with team mailboxes and a newsletter needs one instance, not two. Switching one off hides its screens. Nothing is deleted, so switching it back on finds everything where you left it. One of the two has to stay on — an instance with neither would have navigation with no way back to this page. Each is a view of its own with its own sidebar. With both on, a switcher at the top of the sidebar moves between them; with one on, there is no switcher, because there is nowhere to switch to. Settings is shared. Domains, templates, the email log and delivery reporting are read by a marketing instance as much as by a mailbox one, so they stay visible whatever you choose. ## First run A fresh instance asks three questions before handing you anything: what it is for, what it is called, and what is left to do. The last of those is a live checklist, not a stored list of ticks. An item that stops being true goes back to undone, and leaving halfway loses nothing — every item links to the real screen for that job. You can finish with items outstanding. Waiting on DNS is not a reason to be held on a setup screen. --- # Mailboxes and people Source: https://mailroom-docs.shahriyar.dev/guide/mailboxes # Mailboxes and people ## Mailboxes **Settings → Mailboxes.** A mailbox is one address on one of your domains. There is no limit on how many you have. | Setting | What it does | | --- | --- | | **Display name** | The name on outgoing mail from this address | | **Signature** | Appended when you compose from this address | | **Catch-all** | Collects every unclaimed address on the domain | | **Default** | The address the composer opens with. Only one at a time | | **Colour** | How the mailbox is marked in lists | The address itself cannot be changed after it is made. Make a new mailbox instead — renaming one would orphan the mail already threaded under it. ### Created on first use A mailbox does not have to exist before you send from it. A key that reaches a whole domain can send as `receipts@` on that domain, and the mailbox is created the first time it does. SES already permits it, and nobody wants to hand-create `noreply@` before a script can run. ## People **Settings → People.** You invite somebody by email, and the invitation is sent from a mailbox you choose. An invited person sets a **password** — your colleagues do not each need a GitHub account to read their own mail. Only the owner signs in with GitHub. ### Roles | Role | Can | | --- | --- | | **Owner** | Everything an admin can, **plus** sending domains, the inbound worker, and handing the instance to somebody else | | **Admin** | Mailboxes, people, teams, access, API keys, webhooks, labels, filters and the blocked list | | **Member** | Read and send from the mailboxes they have been given, and nothing else | The split follows who carries the consequences. Adding a domain changes what the company can send as and touches DNS, so it stays at owner level. Running the place day to day is an administrator's work. There can be more than one owner: an owner may promote somebody else to it. An owner's role can only be changed by another owner, and nobody can remove an owner from the list. ### Access Roles say *what kind of thing* somebody may do. **Which mail they can see is separate**, and is decided under **Settings → Access**. Grant a mailbox to a person, or to a **team** so that several people get it at once. A team can have a **lead**, who may change that team's membership without being an admin of the whole instance. A member with no grants sees no mail at all. That is the intended starting point: access is given, not assumed. ## Scope switching The switcher at the top of the mail view changes what you are looking at: - **All mail** — every mailbox you can reach - **One domain** — everything on `example.com` - **One address** — just `you@example.com` The folder list and the search follow whatever is selected, so "unread in support@" is two clicks rather than a query. --- # API keys Source: https://mailroom-docs.shahriyar.dev/guide/api-keys # API keys **Settings → API keys.** A key is how your own code talks to your instance. It is shown once, when it is made, and stored only as a hash — there is no way to read it back. ``` mk_live_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ``` ## Two limits, both checked Every key carries two separate limits, and a call has to pass both. ### Scopes — what kind of call is allowed Presets cover the common cases: | Preset | Means | | --- | --- | | **Full access** | Everything this instance's API can do | | **Send only** | Send mail and check what happened to it. Cannot read your inbox | | **Read only** | Read mail, mailboxes, domains and stats. Cannot change anything | | **Inbox agent** | Read, organise and reply to mail. Cannot manage domains or keys | **Custom** opens nine areas — Sending, Mail, Mailboxes, Domains, Labels, Contacts, Blocked addresses, Webhooks, Statistics — each set to **None**, **Read** or **Manage**. Writing always implies reading, so there is no way to produce a key that may change something it cannot see. ### Reach — which mail those calls may touch | Reach | Means | | --- | --- | | **Everything** | Every mailbox in the account, including ones made later | | **Whole domains** | Every address on those domains, including ones made later | | **Named addresses** | Exactly those mailboxes, and no others | Reach applies **everywhere**, not only to sending. A key limited to `support@example.com` cannot read another inbox, cannot point a webhook at mail it may not read, and cannot list account-wide contacts. Picking a whole domain covers addresses added to it in future, which is what "this key handles support mail" actually means. Picking named addresses is the tighter choice when the set will not grow. ## Rate limit Each key allows **300 calls a minute** unless you set otherwise. Every reply carries the window: ``` X-RateLimit-Limit: 300 X-RateLimit-Remaining: 297 X-RateLimit-Reset: 1800000000 ``` Going over returns `429` with a `Retry-After`. ## Checking a key ```sh curl https://mail.yourdomain.com/api/v1/me \ -H "Authorization: Bearer mk_live_..." ``` This is the first call to make when something is not working: it tells a missing scope apart from a wrong URL in one line. ## Losing one Revoke it. A revoked key stops working immediately and cannot be brought back — make a new one. Mail already sent with it keeps its `api_key_id`, so you can still see what it did. ## Next - [Using the API](/api/) — auth, base URL, the shape of every reply - [Scopes and reach in detail](/api/scopes) - [The Node SDK](/sdk/) — the same thing, typed --- # Test keys Source: https://mailroom-docs.shahriyar.dev/guide/test-mode # Test keys A key made in test mode runs everything a live one runs and stops one step short of handing the message to SES. The mailbox is checked, the blocked list is checked, the template is filled in, the MIME is built, the message appears in Sent, the webhooks fire. Nothing leaves the building, nothing costs anything, and nothing counts against your SES sending quota. ## Making one **Settings → API keys**, fill in the name and the scopes as usual, and turn on **Test key** before creating it. A test key reads `mk_test_…` rather than `mk_live_…`. That is deliberate: a test key that found its way into production config would otherwise look exactly like the real one, and mail that silently never arrives is the kind of failure nobody notices for a week. `GET /api/v1/me` reports which it is: ```json { "object": "api_key", "mode": "test", … } ``` ## Making a bounce happen Since nothing reaches SES, nothing will ever arrive from the event stream to say what became of the message. The recipient decides instead: | Recipient | What the message is made to look like | | --- | --- | | `bounce@…`, `bounced@…` | Bounced | | `complaint@…`, `complained@…` | Marked as spam | | `delay@…` | Still being tried | | Anything else | Delivered | The domain does not matter, only the part before the `@`. Your endpoint hears `email.sent`, then the matching event, in the same shape SES would have produced — plus `simulated: true`: ```json { "id": "evt_…", "type": "email.bounced", "data": { "email": { "id": "msg_…", "status": "bounced", "test": true }, "recipients": ["bounce@example.com"], "detail": "Simulated by a test key", "occurred_at": "2026-09-21T10:00:00.000Z", "simulated": true } } ``` The shape matches on purpose. A receiver you test against a test key must not need a special case, or testing against it proves nothing. The message timeline in the dashboard is written too, so a test send reads the same there as a real one, next to a **test** badge. ## Keeping the two apart Listings and statistics show the side the key is on. A live key sees real mail; a test key sees its own test sends. Either can ask for the other: ```sh curl "https://mail.yourdomain.com/api/v1/emails" # this key's side curl "https://mail.yourdomain.com/api/v1/emails?test=true" # the test side curl "https://mail.yourdomain.com/api/v1/emails?test=false" # the live side curl "https://mail.yourdomain.com/api/v1/emails?test=all" # both ``` `GET /api/v1/messages` and `GET /api/v1/stats` follow the same rule. Statistics are the reason it exists: a bounce rate must never count a bounce somebody asked for. ::: warning This is a view, not a boundary Test mode governs **sending** — a test key cannot put a message in front of a real person. It is not an access control. What a key may read is decided by its [scopes and reach](/api/scopes), the same as any other key, and a test key with `mail:read` can read real mail through its threads. Give a test key the narrow scopes you would give any key you did not fully trust. ::: ## What it is good for - Running your test suite without sending anything, and without an SES sandbox to get out of. - Pointing a webhook receiver at a real send and watching what it does with a bounce, without bouncing a real message. - Letting somebody try an integration against your instance without a key that can put a message in front of a real person. Narrow its scopes as you would any other key — test mode stops the sending, not the reading. ## What it is not It is not a check on whether your mail will land. Nothing reaches SES, so nothing tells you about your reputation, your DNS, or how a real inbox treats your HTML. For that, send to an address you own with a live key. --- # The send queue Source: https://mailroom-docs.shahriyar.dev/guide/queue # The send queue A message that has not gone out yet lives in a queue: one SES could not take right now, and one that was scheduled for later. Both are the same problem — a message that exists and has not been sent — so both are the same table, and the worker carrying them cannot tell them apart. ## Why it exists Handing a message to SES used to be one attempt. If SES throttled the account, or the socket broke, or AWS had a bad minute, the send failed and the message was gone. That is the wrong answer for the one thing an email service is for. ## What is retried, and what is not A refusal that will still be true in an hour is final, and the send fails immediately with nothing recorded: - an unverified identity - a malformed address - a suspended or paused account - credentials that are not valid Anything else is a *not right now*, and goes into the queue: - throttling, and quota limits - an SES outage, or any `5xx` - a dropped or refused connection, a DNS failure, a timeout ## What happens then The attempt gap widens each time — about 30 seconds, then a minute, two, four, eight, and then a quarter of an hour — with a little randomness so a hundred messages queued by one outage do not all wake at once. After eight attempts, roughly three quarters of an hour, it gives up: the message is marked `failed` with the reason on it, and an `email.failed` webhook fires. While it waits, the message sits in Sent marked `queued`, and you can [call it off](/api/emails#call-one-off). ## Where the worker runs Inside the web process. A self-hosted instance is usually one container, and a queue that needs a scheduler wired up separately is a queue that silently does nothing for everyone who skipped that step. Running more than one container is still fine. Jobs are claimed with `FOR UPDATE SKIP LOCKED`, so each worker takes rows no other worker is holding, rather than two of them sending the same message twice. Set `OUTBOX_WORKER=false` to turn it off and drive the queue from somewhere else instead. ::: tip It is at-least-once, not exactly-once If a container is killed in the moment between SES accepting a message and the row being written, the job looks unfinished and is tried again — which sends that message twice. The window is milliseconds wide, and the alternative would be losing a message every time a container restarts. ::: --- # Desktop notifications Source: https://mailroom-docs.shahriyar.dev/guide/notifications # Desktop notifications **Settings → Notifications.** A notice on the desktop when mail arrives, whether or not Mailroom is open in a tab. It uses Web Push, so the browser itself is woken by the push service — there is no tab polling in the background and nothing to leave running. ## Turning it on Two things have to be true. ### 1. The instance needs a key pair Generate one once: ```sh pnpm push:keys ``` It prints three lines to put in your environment: ``` VAPID_PUBLIC_KEY="…" VAPID_PRIVATE_KEY="…" VAPID_SUBJECT="mailto:you@example.com" ``` `VAPID_SUBJECT` is how a push service reaches whoever runs the instance if something goes wrong; any address you actually read is fine. Restart Mailroom after setting them. ::: warning Generate the pair once and leave it alone The keys identify your instance to every browser that has subscribed. Change them and every existing subscription stops working, and everybody has to turn notifications on again. Keep `VAPID_PRIVATE_KEY` secret; the public one is meant to be handed out. ::: Without a pair, the Notifications page says so and offers nothing. Everything else in Mailroom works exactly as before. ### 2. Each person switches it on, per browser **Settings → Notifications → Notify me on this browser.** The browser asks for permission the first time. It is per browser on purpose, because that is what the permission is: allowing it on a laptop says nothing about a phone. Every browser you have switched on is listed under **Devices**, and any of them can be turned off from any of them — useful for a machine you no longer have. **Send a test** does exactly that. Worth using: between the switch and a notice on screen sit a push service, an operating system and a notification daemon, and any of them can swallow it without saying so. ## What gets announced Inbound mail, to a mailbox you are allowed to read. Nothing else — not mail you send, not mail in a mailbox you have no grant on. The notice carries the sender and the subject. Clicking it opens that conversation, reusing a Mailroom window if one is already open. Several messages in one conversation replace each other rather than stacking into a column of the same subject line. ## Requirements | | | | --- | --- | | **https** | Web Push needs a secure connection. On plain http the page says so and the switch is off. `localhost` counts as secure. | | **A modern browser** | Chrome, Edge, Firefox and Safari 16.4+. | | **Outbound network** | The server has to reach the browsers' push services (Google, Mozilla, Apple). A locked-down egress firewall will block it. | ## What it is not Not the live updates in the app — those are a separate stream over SSE, they need no setup, and they are what makes the list fill in while you are looking at it. Not the [browser extension](/guide/extension) either. The extension is a separate thing with its own API key and its own notifications; this one needs nothing installed. ## When it stops working A subscription that a push service reports as gone — somebody cleared their browser data, or revoked the permission — is deleted on the spot, so it never gets retried. One that merely fails is retried for a while and then dropped. If notifications stop for you and nobody else, turn the switch off and on again: that makes a fresh subscription. --- # Browser extension Source: https://mailroom-docs.shahriyar.dev/guide/extension # Browser extension Your inbox in the toolbar, for Chrome, Firefox and Edge. It tells you when mail arrives, shows the conversation, and hands you back to the dashboard the moment you want to write something. It lives in [`packages/extension`](https://github.com/shahriyardx/mailroom/tree/main/packages/extension) and talks to your own instance over the public API. Nothing passes through anybody else, because there is no anybody else: the extension holds an API key you made, and calls your server directly. ## What it does | | | | --- | --- | | **Notifications** | A desktop notification for new unread mail, and the count on the toolbar icon | | **Reading** | The list, the conversation, every message in it, attachments named | | **Triage** | Star, mark read or unread, archive, report spam, delete | | **Search** | The same full-text search the web app uses | | **Views** | Inbox, Unread, Starred, Sent, Archive, Spam, Trash | | **Mailboxes** | Watch every address the key reaches, or pick one | Writing is deliberately not in the popup. **Reply**, **Reply to all** and **Forward** open the conversation in the dashboard with the composer already up, so you get drafts, attachments and your signature instead of a worse version of all three in a 400-pixel box. ## Installing it There is no store listing yet, so it is loaded from a build. ```sh pnpm install pnpm ext:build # chrome, firefox and edge, all three ``` The output lands in `packages/extension/.output/`. ::: code-group ```txt [Chrome and Edge] 1. Open chrome://extensions (edge://extensions) 2. Turn on Developer mode 3. Load unpacked → packages/extension/.output/chrome-mv3 ``` ```txt [Firefox] 1. Open about:debugging#/runtime/this-firefox 2. Load Temporary Add-on… 3. Pick packages/extension/.output/firefox-mv3/manifest.json ``` ::: `pnpm ext:zip` produces store-ready archives instead, and `pnpm ext:dev` starts a browser with the extension loaded and reloading as you edit. ## Connecting it The extension asks for two things, once. 1. **Address** — where your Mailroom lives, for example `https://mail.example.com`. 2. **API key** — from [Settings → API keys](/guide/api-keys). The key needs `mail:read` to show anything, and `mail:write` for the triage buttons. The **Inbox agent** preset is exactly right; **Read only** works too if you would rather the extension could not change anything. Reach works as it does everywhere else: a key restricted to one address shows one address. ### Which mailboxes it watches **Every mailbox** is its own switch, on by default, and it means every mailbox — including addresses you add months from now, without coming back to this screen. Turn it off and you get your own list, which starts empty. Tick the addresses you want; leave it empty and the extension watches nothing at all, shows an empty popup and announces nothing. That is allowed, and it says so on screen. The two are kept apart on purpose. "All of them, whatever they turn out to be" and "these six" look identical on the day you choose them and differ on the day a seventh address is made — so ticking every box by hand does **not** silently become "every mailbox", and unticking your last box does not silently become it either. ### The permission prompt The browser will ask whether the extension may reach that address. It has to: a self-hosted instance has no address that could be declared up front, so the permission is requested for your origin only, at the moment you connect. Say no and there is nothing to read. ## Where the key is kept In `storage.local`, in that browser profile, on that machine. Not in `storage.sync` — that would copy a credential to every machine signed into the same browser account, including ones you never meant to read mail on. Treat it like any other key: if the machine is shared or lost, revoke it in **Settings → API keys** and the extension stops working immediately. ## How new mail is noticed A timer, every two minutes by default, adjustable from one minute to an hour. Not a live stream, though the web app uses one. An extension's background worker is stopped by the browser whenever it feels like it, so a held-open connection would be cut within the minute and spend its life reconnecting. An alarm survives the worker being stopped, which is the property that matters here. The first check after connecting is taken as the starting point rather than announced, so pasting a key does not produce a notification for every unread message you already dealt with elsewhere. ## Reading a message safely Message bodies are sanitised, then drawn inside a sandboxed frame that is not allowed to run scripts. Remote images are held back until you ask for them, the same as in the web app — a remote image in mail is a tracking pixel about as often as it is a picture. --- # Overview Source: https://mailroom-docs.shahriyar.dev/api/ # Using the API Everything lives under one base URL and takes one header. ``` https://mail.yourdomain.com/api/v1 Authorization: Bearer mk_live_... ``` Make a key under **Settings → API keys**. See [API keys](/guide/api-keys) for what the options mean. ## The first call ```sh curl https://mail.yourdomain.com/api/v1/me \ -H "Authorization: Bearer mk_live_..." ``` ```json { "object": "api_key", "id": "key_…", "name": "Production", "scopes": ["*"], "organization": { "id": "org_…", "name": "Acme" }, "reach": { "unrestricted": true, "domains": [], "mailboxes": [] }, "reachable_mailboxes": 4, "rate_limit_per_minute": 300, "api": { "version": "v1", "base_url": "https://mail.yourdomain.com/api/v1", "all_scopes": ["emails:send", "…"], "webhook_events": ["mail.received", "…"] } } ``` Make this call first whenever something is not working. It tells a missing scope apart from a wrong URL in one line, and it needs no scope of its own. ## The shape of a reply Every object carries an `object` field, so a value can be told apart without knowing which call returned it. ```json { "object": "message", "id": "msg_…", "subject": "Hello" } ``` Every list is the same shape: ```json { "object": "list", "data": [ … ], "has_more": true, "next_cursor": "1767225845000|thr_…" } ``` See [Pagination](/api/pagination). Every failure is the same shape: ```json { "error": "No such thread", "code": "not_found" } ``` See [Errors](/api/errors). ## Conventions - **snake_case** in and out. The database is camelCase; the API is not. - **Timestamps are ISO 8601** strings in UTC. - **Addresses** are `{ "name": "Ada", "address": "ada@example.com" }` when read, and a plain string or array of strings when written. `Ada ` is understood. - **Ids are prefixed** — `msg_`, `thr_`, `mbx_`, `lbl_`, `whk_` — so a wrong id in the wrong place is obvious. - **Many lookups take a name** as well as an id. `GET /domains/example.com`, `GET /labels/Receipts` and `DELETE /suppressions/bad@example.net` all work. - **Bodies are at most 30 MB**, which is what caps attachments. ## Every endpoint | Method | Path | Scope | | --- | --- | --- | | `GET` | `/me` | any key | | `POST` | `/emails` | `emails:send` | | `POST` | `/emails/batch` | `emails:send` | | `GET` | `/emails` | `emails:read` | | `GET` | `/emails/:id` | `emails:read` | | `GET` | `/threads` | `mail:read` | | `GET` | `/threads/:id` | `mail:read` | | `PATCH` | `/threads/:id` | `mail:write` | | `DELETE` | `/threads/:id` | `mail:write` | | `POST` | `/threads/:id/reply` | `mail:write` | | `GET` | `/messages` | `mail:read` | | `GET` | `/messages/:id` | `mail:read` | | `PATCH` | `/messages/:id` | `mail:write` | | `GET` | `/messages/:id/raw` | `mail:read` | | `GET` | `/attachments/:id` | `mail:read` | | `GET` | `/mailboxes` | `mailboxes:read` | | `POST` | `/mailboxes` | `mailboxes:write` | | `GET` | `/mailboxes/:id` | `mailboxes:read` | | `PATCH` | `/mailboxes/:id` | `mailboxes:write` | | `DELETE` | `/mailboxes/:id` | `mailboxes:write` | | `GET` | `/domains` | `domains:read` | | `POST` | `/domains` | `domains:write` | | `GET` | `/domains/:id` | `domains:read` | | `POST` | `/domains/:id/verify` | `domains:write` | | `DELETE` | `/domains/:id` | `domains:write` | | `GET` | `/labels` | `labels:read` | | `POST` | `/labels` | `labels:write` | | `GET` | `/labels/:id` | `labels:read` | | `PATCH` | `/labels/:id` | `labels:write` | | `DELETE` | `/labels/:id` | `labels:write` | | `GET` | `/contacts` | `contacts:read` | | `GET` | `/suppressions` | `suppressions:read` | | `POST` | `/suppressions` | `suppressions:write` | | `DELETE` | `/suppressions/:id` | `suppressions:write` | | `GET` | `/webhooks` | `webhooks:read` | | `POST` | `/webhooks` | `webhooks:write` | | `GET` | `/webhooks/:id` | `webhooks:read` | | `PATCH` | `/webhooks/:id` | `webhooks:write` | | `DELETE` | `/webhooks/:id` | `webhooks:write` | | `POST` | `/webhooks/:id/ping` | `webhooks:write` | | `GET` | `/webhook-deliveries` | `webhooks:read` | | `POST` | `/webhook-deliveries/:id/replay` | `webhooks:write` | | `GET` | `/stats` | `stats:read` | ## Prefer not to write this by hand? The [Node SDK](/sdk/) wraps all of it, typed, with retries, pagination and webhook signature checking already done. ## Using an AI assistant? These docs are published in the [llms.txt](https://llmstxt.org) format, so a coding assistant can read the whole API in one fetch rather than crawling pages. | | | | --- | --- | | [`/llms.txt`](https://mailroom-docs.shahriyar.dev/llms.txt) | An index: every page, with a line on what it covers | | [`/llms-full.txt`](https://mailroom-docs.shahriyar.dev/llms-full.txt) | Every page, concatenated. Around 26k tokens | Both are generated from the pages themselves at build time, so they cannot fall behind what is written here. --- # Scopes and reach Source: https://mailroom-docs.shahriyar.dev/api/scopes # Scopes and reach A key carries two limits. Both are checked on every call, and neither substitutes for the other. ## Scopes Scopes say **what kind of call** is allowed. | Scope | Allows | | --- | --- | | `emails:send` | `POST /emails`, `/emails/batch` | | `emails:read` | Listing and reading sent mail | | `mail:read` | Threads, messages, attachments, raw messages | | `mail:write` | Moving, reading, starring, labelling, replying, deleting | | `mailboxes:read` | Listing and reading mailboxes | | `mailboxes:write` | Creating, changing and deleting them | | `domains:read` | Listing and reading domains and their DNS | | `domains:write` | Adding, re-checking and removing them | | `labels:read` | Listing and reading labels | | `labels:write` | Creating, renaming and deleting them | | `contacts:read` | Listing contacts | | `templates:read` | Listing and reading templates, and sending one | | `templates:write` | Creating, changing and deleting them | | `suppressions:read` | Listing blocked addresses | | `suppressions:write` | Blocking and unblocking | | `webhooks:read` | Listing endpoints and deliveries | | `webhooks:write` | Creating, changing, testing, replaying | | `events:read` | Listing the event names your code posts | | `events:write` | `POST /events` — starting an automation from your own code | | `stats:read` | `GET /stats` | | `*` | All of the above, and anything added later | **Writing implies reading.** A key with `mail:write` has `mail:read` without being given it, because "may change but may not see" is a trap that only ever shows up as a 403 in production. Sending a [template](/api/templates) needs `templates:read` as well as `emails:send`, so the ready-made **Send only** choice carries both. A missing scope is a `403`: ```json { "error": "This API key does not have the \"mail:write\" scope", "code": "forbidden", "required_scope": "mail:write", "scopes": ["mail:read", "emails:send"] } ``` ## Reach Reach says **which mail** those calls may touch. | Reach | Means | | --- | --- | | **Everything** | Every mailbox in the account, including ones made later | | **Whole domains** | Every address on those domains, including ones made later | | **Named addresses** | Exactly those mailboxes | Reach is enforced everywhere, not only on sending: - `GET /threads` returns only threads in mailboxes the key reaches. - `GET /domains` returns only domains it holds. - `GET /contacts` returns `403` for any key that is not unrestricted, because contacts are kept per account and there is no honest way to narrow them. - `POST /domains` returns `403` for the same reason — adding a domain changes the account, not one corner of it. - A webhook cannot be created without a mailbox by a key that does not reach the whole account, or it would be a way to receive mail the key cannot read. ### Something out of reach is a 404, not a 403 ```json { "error": "No such thread", "code": "not_found" } ``` Deliberately. A `403` would confirm the object exists, which lets somebody map what they cannot see by asking about it. ## Sending, specifically | The key holds | May send as | | --- | --- | | Everything | Any address on any verified domain. The mailbox is made on first use | | Whole domains | Any address on those domains. The mailbox is made on first use | | Named addresses | Exactly those addresses | This is why a whole-domain key is the right choice for transactional mail: `receipts@`, `noreply@` and `alerts@` all work without anybody creating them first. ## Picking one Give each integration the narrowest key that does its job. | The job | Scopes | Reach | | --- | --- | --- | | A billing service sending receipts | `emails:send` | the `billing.` domain | | A dashboard showing delivery health | `emails:read`, `stats:read` | everything | | A bot that answers support mail | `mail:read`, `mail:write`, `emails:send` | `support@` | | A backup script | `mail:read` | everything | --- # Pagination Source: https://mailroom-docs.shahriyar.dev/api/pagination # Pagination Every list returns one page and, when there is more, an opaque cursor. ```json { "object": "list", "data": [ … ], "has_more": true, "next_cursor": "1767225845000|thr_9f2c…" } ``` Pass it back as `cursor`: ```sh curl "https://mail.yourdomain.com/api/v1/threads?cursor=1767225845000%7Cthr_9f2c…" \ -H "Authorization: Bearer mk_live_..." ``` `next_cursor` is **opaque**. It happens to be a sort value and an id joined by a pipe, which is what keeps paging stable when many rows share a timestamp, but nothing should parse it — hand it back untouched. ## Size ``` ?limit=50 ``` At most **100**, and **25** by default. ## A full walk ```sh cursor="" while :; do page=$(curl -s "https://mail.yourdomain.com/api/v1/threads?limit=100&cursor=$cursor" \ -H "Authorization: Bearer $KEY") echo "$page" | jq -c '.data[]' [ "$(echo "$page" | jq -r .has_more)" = "true" ] || break cursor=$(echo "$page" | jq -r .next_cursor) done ``` The [SDK](/sdk/reading#paging) does this as an `for await` loop. ## Which lists page | Pages | One shot | | --- | --- | | `/emails` | `/mailboxes` | | `/threads` | `/domains` | | `/messages` | `/labels` | | `/contacts` | `/webhooks` | | `/suppressions` | | | `/webhook-deliveries` | | The one-shot lists cannot grow without bound, so paging them would be ceremony for nothing. ## Ordering Newest first, by the field that matters for the thing being listed: | List | Sorted by | | --- | --- | | `/emails` | `created_at` | | `/threads` | `last_message_at` | | `/messages` | `received_at` | | `/contacts` | `last_seen_at`, or `message_count` with `?order=frequent` | | `/suppressions` | `created_at` | | `/webhook-deliveries` | `created_at` | ## Rows that move Paging is a snapshot taken row by row, not a transaction. A thread that gets a new message while you are half way through a walk moves to the front and you may see it twice; one that is deleted disappears. For anything that has to be exact, filter on a fixed window with `since` and `until` rather than walking an open-ended list. --- # Errors Source: https://mailroom-docs.shahriyar.dev/api/errors # Errors Anything other than a `2xx` returns the same shape. ```json { "error": "A sentence you can log", "code": "not_found" } ``` `error` is for a human reading a log. `code` is for a program deciding what to do. ## The codes | Status | `code` | Means | Retry? | | --- | --- | --- | --- | | 401 | `unauthorized` | Key missing, mistyped or revoked | No | | 403 | `forbidden` | Missing a scope, or the call is account-wide and the key is not | No | | 404 | `not_found` | No such object, or none this key may reach | No | | 409 | `conflict` | Already exists, or a destructive call needs its confirmation flag | No | | 413 | `payload_too_large` | Over 30 MB. Usually an attachment | No | | 422 | `invalid_request` | A field is wrong. `param` names it | No | | 429 | `rate_limited` | Too many calls this minute | Yes, after `Retry-After` | | 500 | `server_error` | The instance failed | Yes | ## A missing scope ```json { "error": "This API key does not have the \"mail:write\" scope", "code": "forbidden", "required_scope": "mail:write", "scopes": ["mail:read"] } ``` `required_scope` is the one to add. ## A bad field ```json { "error": "to: Required, subject: Expected string, received number", "code": "invalid_request", "param": "to" } ``` Every problem is listed in `error`; `param` names the first, which is enough to highlight a form field. ## Rate limiting ``` HTTP/1.1 429 Retry-After: 43 X-RateLimit-Limit: 300 X-RateLimit-Remaining: 0 X-RateLimit-Reset: 1800000000 ``` ```json { "error": "Too many requests. Slow down.", "code": "rate_limited" } ``` ## Why 404 and not 403 A key that cannot reach an object is told the object does not exist. That is on purpose: a `403` confirms it *does* exist, which turns "no access" into a way to enumerate what you cannot see. So a `404` means one of two things, and the API will not tell you which: - It is genuinely not there - It is outside this key's [reach](/api/scopes#reach) Check with `GET /me` when you are unsure. ## Partial success Two endpoints can half-work, and neither uses an error status for it. **Batch sending** returns `207` when some messages failed: ```json { "object": "batch", "sent": 2, "failed": 1, "data": [ { "index": 0, "ok": true, "id": "msg_…" }, { "index": 1, "ok": false, "error": "…", "status": 422 }, { "index": 2, "ok": true, "id": "msg_…" } ] } ``` **Webhook ping and replay** return `502` with a full result body when your endpoint was unreachable. The call worked; the endpoint did not. ```json { "object": "webhook_ping", "succeeded": false, "status_code": 500, "response_body": "Internal Server Error", "error": "Endpoint replied 500" } ``` --- # Idempotency and limits Source: https://mailroom-docs.shahriyar.dev/api/idempotency # Idempotency and limits ## Sending exactly once A send that times out leaves you with a hard question: did it go? Send an `Idempotency-Key` and the question disappears. ```sh curl -X POST https://mail.yourdomain.com/api/v1/emails \ -H "Authorization: Bearer mk_live_..." \ -H "Idempotency-Key: receipt-4821" \ -H "Content-Type: application/json" \ -d '{ "from": "receipts@example.com", "to": "a@b.c", "subject": "Receipt" }' ``` Repeat the call with the same key and you get the **first reply back**, not a second message. The replay carries a header: ``` Idempotency-Replayed: true ``` Keys are remembered for **24 hours**, per endpoint. ### Use something meaningful The key should come from the thing you are sending about — `receipt-4821`, `order-19023-shipped` — not from a random UUID generated at call time. A fresh UUID on a retry is no protection at all, because it is a different key. ### Same key, different body ```json { "error": "This idempotency key was used with a different request", "code": "conflict" } ``` That is the guard working. Either you reused a key you should not have, or something changed between the first call and the retry. ### Where it works `POST /emails` and `POST /emails/batch`. For a batch, the whole array is what the key covers. ## Rate limits Each key allows **300 calls a minute** unless it was given its own limit. Every reply carries the window: ``` X-RateLimit-Limit: 300 X-RateLimit-Remaining: 297 X-RateLimit-Reset: 1800000000 ``` `X-RateLimit-Reset` is Unix seconds. Going over returns `429` with `Retry-After` in seconds. Wait that long — do not hammer, because a fixed window means the whole allowance returns at once and a tight retry loop simply spends it again. ::: tip It is per container The counter lives in the process, so two containers allow twice the stated rate. It exists to stop a runaway loop from emptying your SES quota, not to meter a plan. ::: ## The SES quota is separate The rate limit is Mailroom's. **SES has its own**, and it is the one that actually stops mail going out. It is a rolling 24-hour window, not a daily allowance: each message stops counting exactly 24 hours after it was sent. See [Sending domains](/guide/domains#the-sending-limit). A new SES account is in the sandbox — 200 a day, verified recipients only. Ask AWS for production access before you rely on it. ## Body size 30 MB, which caps attachments. Over it: ```json { "error": "The request body is too large", "code": "payload_too_large" } ``` At most **20 attachments** on one message. Remember base64 adds about a third, so a 30 MB body is roughly 22 MB of files. --- # Emails Source: https://mailroom-docs.shahriyar.dev/api/emails # Emails Sending, and looking at what was sent. ## Send one ``` POST /api/v1/emails ``` Scope: `emails:send` ```sh curl -X POST https://mail.yourdomain.com/api/v1/emails \ -H "Authorization: Bearer mk_live_..." \ -H "Idempotency-Key: receipt-4821" \ -H "Content-Type: application/json" \ -d '{ "from": "Receipts ", "to": ["customer@example.net"], "cc": "manager@example.net", "reply_to": "support@example.com", "subject": "Your receipt", "html": "

Thanks for your order.

", "text": "Thanks for your order.", "headers": { "X-Order-Id": "4821" } }' ``` | Field | | | | --- | --- | --- | | `from` | **required** | An address on a verified domain. `Name ` works | | `to` | **required** | A string or an array | | `cc`, `bcc` | | A string or an array | | `reply_to` | | One address | | `subject` | | Defaults to empty | | `html`, `text` | | Send either, or both | | `headers` | | Extra headers, as a flat object | | `template`, `template_id` | | A [saved template](/api/templates) to send instead of a body | | `data` | | The values that template asks for | | `scheduled_at` | | Hold it until then. See [Sending later](#sending-later) | | `thread_id` | | Add this message to an existing thread | | `in_reply_to`, `references` | | Threading headers, if you are building them yourself | | `attachments` | | At most 20. See below | Returns `202`: ```json { "id": "msg_…", "message_id": "<…@example.com>", "ses_message_id": "0100018f…", "thread_id": "thr_…", "from": "receipts@example.com", "to": ["customer@example.net"], "subject": "Your receipt", "status": "sent", "scheduled_at": null, "test": false } ``` `202`, not `200`: SES has accepted it, and whether it was *delivered* comes later — as a `status` on the message, and as an [`email.delivered` webhook](/webhooks/events). ### What `status` means | | | | --- | --- | | `sent` | Handed to SES. The usual answer | | `scheduled` | Held until `scheduled_at` | | `queued` | SES could not take it right now. It will keep trying | | `delivered`, `bounced`, … | A [test key](/guide/test-mode) sent it, and the outcome was simulated | `queued` is not an error and needs nothing from you. A send that SES refuses for a reason that will still be true in an hour — an unverified identity, a malformed address, a suspended account — returns an error instead and records nothing. Anything else, from throttling to a dropped socket, goes into a queue and is retried with a widening gap between attempts, up to eight times over about three quarters of an hour. `email.sent` fires when it goes out, and `email.failed` if the attempts run out. ## Sending later Set `scheduled_at` and the message is written to Sent straight away, marked `queued` with a time on it, and handed over when that time comes. ```sh curl -X POST https://mail.yourdomain.com/api/v1/emails \ -H "Authorization: Bearer mk_live_..." \ -H "Content-Type: application/json" \ -d '{ "from": "reminders@example.com", "to": "customer@example.net", "subject": "Your appointment tomorrow", "text": "See you at 10.", "scheduled_at": "in 2 hours" }' ``` Any of these forms works: | | | | --- | --- | | `"2026-10-01T09:00:00Z"` | ISO 8601 | | `1790000000` | Unix time, seconds or milliseconds | | `"in 30 minutes"` | `second`, `minute`, `hour` or `day`, singular or plural | A time that has already passed sends now. At most 30 days ahead. ### Call one off ``` POST /api/v1/emails/:id/cancel ``` Scope: `emails:send` Works on anything still waiting — scheduled, or queued because SES was busy. Returns the message with `status: "canceled"`. Answers `409` once a worker has picked the message up. At that point it is on its way to SES and there is nothing left to stop, and saying otherwise would be a lie you would go on to build on. ### Move one ``` PATCH /api/v1/emails/:id ``` Scope: `emails:send` ```json { "scheduled_at": "2026-10-01T09:00:00Z" } ``` Same forms, and the same `409` once it has been picked up. ### Attachments ```json { "attachments": [ { "filename": "invoice.pdf", "content": "JVBERi0xLjQKJ…", "content_type": "application/pdf" }, { "filename": "logo.png", "content": "iVBORw0KGgo…", "content_id": "logo" } ] } ``` `content` is base64; a `data:` prefix is stripped for you. Setting `content_id` embeds the file instead of attaching it, so `` in your HTML shows it inline. ## Send a batch ``` POST /api/v1/emails/batch ``` Scope: `emails:send` ```json [ { "from": "news@example.com", "to": "a@example.net", "subject": "Hi", "text": "…" }, { "from": "news@example.com", "to": "b@example.net", "subject": "Hi", "text": "…" } ] ``` An object with an `emails` array works too. Up to **100** messages. Every one is attempted, in order, one at a time — SES meters sends per second, and firing a hundred at once is the fastest way to be throttled for all of them. `202` when all were accepted, `207` when some were not: ```json { "object": "batch", "sent": 1, "failed": 1, "data": [ { "index": 0, "ok": true, "id": "msg_…", "thread_id": "thr_…" }, { "index": 1, "ok": false, "error": "This API key cannot send as x@y.z", "status": 403 } ] } ``` So you can branch on the status without counting. ## List what was sent ``` GET /api/v1/emails ``` Scope: `emails:read` | Filter | | | --- | --- | | `status` | One or several of `queued`, `sent`, `delivered`, `bounced`, `complained`, `rejected`, `delayed`, `failed`, `canceled`. Comma-separated | | `from` | Exact sender address | | `to` | Exact recipient address | | `subject` | Substring | | `q` | Full text over subject and body | | `opened` | `true` or `false` | | `api_key_id` | Only mail sent by one key | | `since`, `until` | ISO dates | | `mailbox_id`, `mailbox`, `domain` | Narrow to part of the account | | `test` | `true` for the test side, `all` for both. See [Test keys](/guide/test-mode) | | `limit`, `cursor` | See [Pagination](/api/pagination) | ```sh curl "https://mail.yourdomain.com/api/v1/emails?status=bounced,complained&since=2026-09-01" \ -H "Authorization: Bearer mk_live_..." ``` Drafts are excluded: they are outbound, but they have not been sent. So is mail written by a [test key](/guide/test-mode), unless you ask for it. Everything still waiting is `status=queued`; the ones with a `scheduled_at` are waiting for the clock, and the rest are waiting for SES. ## Read one ``` GET /api/v1/emails/:id ``` Scope: `emails:read` Returns the message with its body, its files, and **every SES event seen for it so far**: ```json { "object": "message", "id": "msg_…", "status": "bounced", "error": "smtp; 550 5.1.1 user unknown", "opened_at": null, "open_count": 0, "text": "…", "html": "…", "attachments": [ … ], "events": [ { "object": "event", "type": "send", "occurred_at": "…" }, { "object": "event", "type": "bounce", "recipient": "a@b.c", "detail": "…", "occurred_at": "…" } ] } ``` The id from a send works, and so does the **SES message id** — which is what a bounce report or a webhook hands you. ## A note on opens `opened_at` means the tracking image was loaded. Apple Mail and Gmail fetch images through their own servers, so an open is evidence of **delivery**, not proof anybody read it. --- # Templates Source: https://mailroom-docs.shahriyar.dev/api/templates # Templates A saved subject and body with holes in it, sent by id. The point is that the wording stops living inside whatever service does the sending. Changing a receipt should not need a deploy, and the same receipt should read the same whichever service sent it. ## Sending one Send a `template` — its id — instead of `html` and `text`, and a `data` object holding the values it asks for. ```sh curl -X POST https://mail.yourdomain.com/api/v1/emails \ -H "Authorization: Bearer mk_live_..." \ -H "Content-Type: application/json" \ -d '{ "from": "receipts@example.com", "to": "customer@example.net", "template": "tpl_…", "data": { "name": "Ada", "amount": "£10.00" } }' ``` A `subject` sent alongside a template wins over the saved one, so a one-off variation needs no second template. ## The language It is deliberately not one: | | | | --- | --- | | {{ name }} | The value, with HTML escaped | | {{{ body }}} | The value as it is, for markup you meant | | {{ user.name }} | A path into a nested object | That is all of it. No loops, no conditionals, no function calls. A template that needs logic has quietly become code, and code belongs in the service doing the sending, where it can be reviewed and tested. ::: warning A missing value is an error A name with no value in `data` answers `422` and says which one is missing. It does not become an empty string: `Hi ,` arriving at a customer is worse than an error, and an empty string cannot be told apart later from a value that really was empty. ::: {{ }} escapes what it inserts, so a name arriving from a signup form cannot write tags into mail sent under your own domain. Use {{{ }}} only for markup you produced yourself. ## Save one ``` POST /api/v1/templates ``` Scope: `templates:write` ```sh curl -X POST https://mail.yourdomain.com/api/v1/templates \ -H "Authorization: Bearer mk_live_..." \ -H "Content-Type: application/json" \ -d '{ "name": "Receipt", "subject": "Your receipt, {{ name }}", "html": "

Hello {{ name }}, you paid {{ amount }}.

", "text": "Hello {{ name }}, you paid {{ amount }}." }' ``` | Field | | | | --- | --- | --- | | `name` | **required** | What a person calls it | | `description` | | A note for whoever finds it later | | `subject` | | May contain placeholders | | `html`, `text` | | Send either, or both | Returns `201` with the saved template and, usefully, everything it asks for: ```json { "object": "template", "id": "tpl_…", "name": "Receipt", "subject": "Your receipt, {{ name }}", "variables": ["name", "amount"], "created_at": "2026-09-21T10:00:00.000Z", "updated_at": "2026-09-21T10:00:00.000Z" } ``` The `id` is what your code sends by. It never changes, so renaming a template breaks nothing. Two templates may share a name. ## List them ``` GET /api/v1/templates ``` Scope: `templates:read` By name. There are never many, so they arrive in one page. ## Read one ``` GET /api/v1/templates/:id ``` Scope: `templates:read` By its id. ## Change one ``` PATCH /api/v1/templates/:id ``` Scope: `templates:write` Send only what changes; the rest is left alone. ## Delete one ``` DELETE /api/v1/templates/:id ``` Scope: `templates:write` Mail already sent from it is unaffected — the wording was copied into the message when it went out, not looked up afterwards. ## In the dashboard **Settings → Templates** does all of this, with a preview that fills each hole with its own name, so nothing in the preview can be mistaken for real data. --- # Threads Source: https://mailroom-docs.shahriyar.dev/api/threads # Threads A thread is a conversation. Inbound mail lives in threads, and this is the endpoint that makes an inbox readable from outside the app. ## List ``` GET /api/v1/threads ``` Scope: `mail:read` | Filter | | | --- | --- | | `folder` | `inbox`, `sent`, `drafts`, `archive`, `spam`, `trash`, or `all` | | `label_id` / `label` | By id or by name | | `q` | Full text across every message in the thread | | `unread` | `true` for threads with anything unread | | `starred`, `has_attachments` | `true` or `false` | | `participant` | Anybody on the conversation, by address | | `subject` | Substring | | `since`, `until` | Against `last_message_at` | | `mailbox_id`, `mailbox`, `domain` | Narrow to part of the account | | `limit`, `cursor` | See [Pagination](/api/pagination) | ```json { "object": "thread", "id": "thr_…", "mailbox": "support@example.com", "subject": "Refund for order 4821", "snippet": "Hi — I'd like to return…", "folders": ["inbox"], "participants": [{ "name": "Ada", "address": "ada@example.net" }], "message_count": 3, "unread_count": 1, "is_starred": false, "has_attachments": true, "last_message_at": "2026-09-20T14:03:11.000Z", "labels": [{ "object": "label", "id": "lbl_…", "name": "Refunds" }] } ``` `folders` is a list because a thread can have messages in more than one — a conversation you replied to sits in both `inbox` and `sent`. ## Read one ``` GET /api/v1/threads/:id ``` Scope: `mail:read` Returns the thread with **every message in it**, bodies and attachments included. Add `?include_body=false` for a lighter reply when only the shape matters. ## Change one ``` PATCH /api/v1/threads/:id ``` Scope: `mail:write` ```json { "folder": "archive", "is_read": true, "is_starred": false, "add_labels": ["Refunds"], "remove_labels": ["Needs reply"] } ``` Every field is optional and only what you send is changed, so archiving and marking read is one call rather than a read followed by two writes. Labels may be given **by name or by id**. An unknown one is a `422` and **nothing is changed** — the labels are resolved before anything is written, so you never get an error alongside a move that already happened. Drafts stay where they are when `folder` is set. Moving one into the archive would lose the only place the composer looks for it. Firing this also sends a [`thread.updated` webhook](/webhooks/events). ## Reply ``` POST /api/v1/threads/:id/reply ``` Scope: `mail:write` ```json { "text": "Refunded — sorry for the trouble.", "reply_all": true } ``` Who it goes to, what it is called, and the headers that keep it threaded are all read off the last message. Each can be overridden: | Field | | | --- | --- | | `text`, `html` | One is required | | `reply_all` | Also answer everyone else on the last message | | `to`, `cc`, `bcc` | Replace the worked-out recipients entirely | | `subject` | Defaults to `Re: …` | | `quote` | Append the message being answered. **On by default** | | `headers`, `attachments` | As on a normal send | Returns `202` with the same body as a send. ## Delete ``` DELETE /api/v1/threads/:id ``` Scope: `mail:write` To the trash, and **out of it for good on a second call**. `?permanent=true` skips the trash. ```json { "object": "thread", "id": "thr_…", "deleted": true, "permanent": false } ``` --- # Messages and files Source: https://mailroom-docs.shahriyar.dev/api/messages # Messages and files Threads are the better way to read a conversation. These endpoints are for when a program wants **messages themselves** — everything that arrived since a stamp, everything from one sender, everything unread. ## List ``` GET /api/v1/messages ``` Scope: `mail:read` | Filter | | | --- | --- | | `direction` | `inbound` or `outbound` | | `folder` | A folder name, or `all` | | `thread_id` | Everything in one conversation | | `drafts` | `true` for only drafts, `false` to exclude them | | `unread`, `starred` | `true` or `false` | | `from` | Exact sender address | | `to` | Exact recipient address | | `subject` | Substring | | `q` | Full text over subject, body and sender | | `since`, `until` | Against `received_at` | | `include_body` | `true` to include `text` and `html`. Off by default | | `mailbox_id`, `mailbox`, `domain` | Narrow to part of the account | | `limit`, `cursor` | See [Pagination](/api/pagination) | Bodies are left out by default because they are large and a list of fifty of them is mostly HTML you did not ask for. ## Read one ``` GET /api/v1/messages/:id ``` Scope: `mail:read` The message with its body, its files and its events. ```json { "object": "message", "id": "msg_…", "thread_id": "thr_…", "mailbox": "support@example.com", "message_id": "", "from": { "name": "Ada", "address": "ada@example.net" }, "to": [{ "name": null, "address": "support@example.com" }], "subject": "Refund for order 4821", "folder": "inbox", "direction": "inbound", "is_read": false, "spf": "pass", "dkim": "pass", "dmarc": "pass", "spam_score": 0, "mailed_by": "mail.example.net", "signed_by": "example.net", "tls": "TLS1.3", "text": "…", "html": "…", "attachments": [ … ], "events": [ … ] } ``` `spf`, `dkim` and `dmarc` are what the receiving worker saw. Mailroom does not act on them; it records them so you can. ## Change one ``` PATCH /api/v1/messages/:id ``` Scope: `mail:write` ```json { "is_read": true, "is_starred": true } ``` Read and star **one message**, rather than the whole thread. The thread's counts are recomputed afterwards. ## The original message ``` GET /api/v1/messages/:id/raw ``` Scope: `mail:read` Returns `message/rfc822` bytes — the message exactly as it arrived. Pipe it into a MIME parser, re-send it, or keep it for an audit. ```sh curl "https://mail.yourdomain.com/api/v1/messages/msg_…/raw" \ -H "Authorization: Bearer mk_live_..." \ -o message.eml ``` Only **inbound** mail has one. Outbound mail is assembled at send time and its wire form is not stored, so asking for it returns `404`. A `404` here can also mean the row outlived the object — a bucket lifecycle rule, or a restore that did not bring everything back. ## Attachments ``` GET /api/v1/attachments/:id ``` Scope: `mail:read` ```json { "object": "attachment", "id": "att_…", "message_id": "msg_…", "filename": "invoice.pdf", "content_type": "application/pdf", "size_bytes": 84213, "content_id": null, "is_inline": false, "download_url": "https://…", "download_url_expires_in": 300 } ``` `download_url` is a signed link straight to storage, good for **five minutes**. Use it for anything large or headed to a browser: it does not spend your rate limit and the bytes never pass through the app. For a small file, `?download=true` returns the bytes directly and saves a second request. An attachment is only reachable **through a message this key may read**. Staged uploads, which have no message yet, are not reachable at all. --- # Mailboxes Source: https://mailroom-docs.shahriyar.dev/api/mailboxes # Mailboxes The addresses on your domains. ## List ``` GET /api/v1/mailboxes ``` Scope: `mailboxes:read` Returns every address **this key can reach**, which is the quickest way for a client to discover what it is allowed to do. `?domain=example.com` narrows it. ```json { "object": "mailbox", "id": "mbx_…", "address": "support@example.com", "domain": "example.com", "domain_id": "dom_…", "display_name": "Support", "signature": "— The team", "is_catch_all": false, "is_default": true, "color": "#6366f1", "created_at": "2026-01-04T09:12:00.000Z" } ``` ## Read one ``` GET /api/v1/mailboxes/:id ``` Scope: `mailboxes:read` ## Create ``` POST /api/v1/mailboxes ``` Scope: `mailboxes:write` ```json { "address": "billing@example.com", "display_name": "Billing", "signature": "— Accounts", "is_catch_all": false, "is_default": false, "color": "#0ea5e9" } ``` The address must sit on a domain this account has verified, **or under one**. A subdomain of a verified domain needs no identity of its own, so anything the covering domain reaches is allowed. A key that holds whole domains may add to them. A key that names addresses holds exactly those, and naming one more is not its to do — that is a `403`. Setting `is_default` clears it everywhere else. Only one at a time, or the composer has to choose between them. ## Change one ``` PATCH /api/v1/mailboxes/:id ``` Scope: `mailboxes:write` ```json { "display_name": "Billing team", "signature": null } ``` The **address itself cannot change**. Make a new mailbox instead — renaming one would orphan the mail already threaded under it. Send `signature: null` to clear it. ## Delete ``` DELETE /api/v1/mailboxes/:id?confirm=true ``` Scope: `mailboxes:write` ::: danger This deletes the mail in it Without `?confirm=true` the call returns `409` and does nothing. A mistyped id should not empty an inbox. ::: ```json { "object": "mailbox", "id": "mbx_…", "deleted": true } ``` ## Created on first use A mailbox does not have to exist before you send from it. A key that reaches a whole domain can send as any address on it, and the mailbox is created the first time it does — SES already permits it, and code sends from `noreply@` and `receipts@` that nobody would think to create by hand. --- # Domains Source: https://mailroom-docs.shahriyar.dev/api/domains # Domains What this account can send from, and the DNS each one needs. ## List ``` GET /api/v1/domains ``` Scope: `domains:read` A key limited to some domains sees those. A domain name and its records are not secret, but they are not that key's business either. ```json { "object": "domain", "id": "dom_…", "name": "example.com", "region": "us-east-1", "status": "verified", "sending_enabled": true, "dkim_status": "verified", "dkim_origin": "AWS_SES", "mail_from_domain": "mail.example.com", "mail_from_status": "verified", "spf_verified": true, "dmarc_verified": true, "inherited_from": null, "auto_create_mailboxes": false, "imported": false, "last_checked_at": "2026-09-21T08:00:00.000Z", "records": [ { "kind": "CNAME", "name": "abc123._domainkey.example.com", "value": "abc123.dkim.amazonses.com", "purpose": "DKIM signing", "required": true } ] } ``` `status` is one of `pending`, `verified`, `failed`, `temporary_failure`, `not_started`. `inherited_from` is set when the domain is a **subdomain covered by a parent**. Such a domain has an empty `records` array, because there is nothing to publish. ## Read one ``` GET /api/v1/domains/:id ``` Scope: `domains:read` Takes the **name** as well as the id: ```sh curl https://mail.yourdomain.com/api/v1/domains/example.com \ -H "Authorization: Bearer mk_live_..." ``` ## Add ``` POST /api/v1/domains ``` Scope: `domains:write` ```json { "name": "example.com" } ``` Creates the identity in SES and returns the records to publish. Returns `201`. Only a key that reaches the **whole account** may do this, because adding a domain changes the account rather than one corner of it. A narrower key gets `403`. ## Re-check ``` POST /api/v1/domains/:id/verify ``` Scope: `domains:write` Asks SES where the identity stands and probes SPF and DMARC in DNS, then returns the domain as it now is. This is what a setup script polls after publishing records. ```sh until curl -s https://mail.yourdomain.com/api/v1/domains/example.com/verify \ -X POST -H "Authorization: Bearer $KEY" | jq -e '.sending_enabled' >/dev/null do sleep 30; done ``` ## Remove ``` DELETE /api/v1/domains/:id ``` Scope: `domains:write` Removes it from Mailroom. Add `?delete_in_ses=true` to delete the SES identity too. ::: warning delete_in_ses cannot be undone And other instances, or other applications on the same AWS account, may be relying on that identity. ::: ```json { "object": "domain", "id": "dom_…", "name": "example.com", "deleted": true, "deleted_in_ses": false } ``` --- # Labels and contacts Source: https://mailroom-docs.shahriyar.dev/api/labels # Labels and contacts ## Labels The labels threads are filed under. Scoped to the account, not to a mailbox. ### List ``` GET /api/v1/labels ``` Scope: `labels:read` ```json { "object": "label", "id": "lbl_…", "name": "Refunds", "color": "#64748b" } ``` ### Read one ``` GET /api/v1/labels/:id ``` Scope: `labels:read` Takes the **name** as well as the id — `GET /labels/Refunds` works, which matters because an id is not something a script writer has to hand. ### Create ``` POST /api/v1/labels ``` Scope: `labels:write` ```json { "name": "Refunds", "color": "#64748b" } ``` `color` is a hex value like `#64748b`, and defaults to that. Names are unique per account, so a repeat is `409`. ### Rename or recolour ``` PATCH /api/v1/labels/:id ``` Scope: `labels:write` ```json { "name": "Returns", "color": "#0ea5e9" } ``` ### Delete ``` DELETE /api/v1/labels/:id ``` Scope: `labels:write` The label goes; the threads it was on stay. ### Putting one on a thread Labels are applied through the thread, not through the label: ```sh curl -X PATCH https://mail.yourdomain.com/api/v1/threads/thr_… \ -H "Authorization: Bearer $KEY" \ -H "Content-Type: application/json" \ -d '{ "add_labels": ["Refunds"] }' ``` See [Threads](/api/threads#change-one). ## Contacts Everyone this account has written to or heard from, built automatically as mail moves. ``` GET /api/v1/contacts ``` Scope: `contacts:read` | Filter | | | --- | --- | | `q` | Matches the address or the name | | `order` | `recent` (default) or `frequent` | | `limit`, `cursor` | See [Pagination](/api/pagination) | ```json { "object": "contact", "id": "con_…", "address": "ada@example.net", "name": "Ada Lovelace", "message_count": 27, "last_seen_at": "2026-09-20T14:03:11.000Z" } ``` ::: warning Only an unrestricted key can read these Contacts are kept for the **whole account**, so there is no honest way to narrow them to part of it. A key that reaches one department must not be able to read every address the company has ever written to, so it gets `403`. ::: There is no write endpoint. A contact appears when mail does. --- # Blocked addresses Source: https://mailroom-docs.shahriyar.dev/api/suppressions # Blocked addresses Addresses this account will not send to again. Bounces and complaints fill this in automatically. ## Why it exists SES judges you on your bounce and complaint rates. Above **5%** bounces or **0.1%** complaints it starts warning, and it will suspend an account that keeps going. Continuing to send to an address that hard-bounced is the fastest way there. So a hard bounce or a spam complaint adds the address here, and sends to it stop. ## List ``` GET /api/v1/suppressions ``` Scope: `suppressions:read` | Filter | | | --- | --- | | `q` | Substring of the address | | `limit`, `cursor` | See [Pagination](/api/pagination) | ```json { "object": "suppression", "id": "sup_…", "address": "gone@example.net", "reason": "Hard bounce: smtp; 550 5.1.1 user unknown", "created_at": "2026-09-14T11:20:03.000Z" } ``` ## Block one by hand ``` POST /api/v1/suppressions ``` Scope: `suppressions:write` ```json { "address": "unsubscribed@example.net", "reason": "Asked to stop" } ``` Returns `201` when it is new and `200` when it was already blocked — blocking an already-blocked address is not an error, it is the state you asked for. Useful for honouring an unsubscribe from your own application, so the block lives in one place rather than two. ## Unblock ``` DELETE /api/v1/suppressions/:id ``` Scope: `suppressions:write` Takes the **address** as well as the id: ```sh curl -X DELETE "https://mail.yourdomain.com/api/v1/suppressions/gone%40example.net" \ -H "Authorization: Bearer mk_live_..." ``` ::: warning Think before you do The address is on this list because mail to it bounced or was reported as spam. Sending again risks the account's own sending reputation, and the reputation is shared by every domain on it. Unblocking is right when the address was blocked by mistake, or the mailbox has genuinely been fixed. It is not a way to retry a bad list. ::: ```json { "object": "suppression", "id": "sup_…", "address": "gone@example.net", "deleted": true } ``` --- # Events Source: https://mailroom-docs.shahriyar.dev/api/events # Events Things that happen in your own product. Post one and whatever [automation](/guide/automations) is waiting for it starts, for that person. This is the outbound direction only — your code telling Mailroom. For Mailroom telling your code about mail, see [Webhooks](/api/webhooks). ## Post an event ``` POST /api/v1/events ``` Scope: `events:write` ```json { "event": "trial.ended", "email": "person@example.com", "name": "Pat Doe", "fields": { "plan": "pro", "order": "A-19" }, "consent_source": "signed up at checkout" } ``` | Field | | | | --- | --- | --- | | `event` | required | The name. Lowercased and tidied, so `Trial.Ended` and `trial.ended` are the same event | | `email` | required | Who it happened to | | `name` | optional | Used only if they have to be added to the list | | `fields` | optional | Merged onto the person before the flow starts | | `consent_source` | optional | Where consent came from. Only used when they are not on the list yet | The reply names every automation that heard it, and what happened to that person in each: ```json { "event": "trial.ended", "declared": true, "matched": 1, "automations": [ { "id": "aut_…", "name": "After the trial", "status": "started" } ] } ``` | `status` | Meaning | | --- | --- | | `started` | They are at the top of the flow | | `restarted` | They had finished it before; they are back at the top | | `already_running` | They are part-way through it, so nothing was done | | `skipped` | Nothing happened. `reason` says why | The same reply carries `stopped`: flows this event **ended**, because it was what they were for. ```json { "stopped": [{ "id": "aut_…", "name": "Cart recovery" }] } ``` And `resumed`: flows where this person was sitting on a **Wait for an event** box for this name. They move on down its *arrived* side straight away. ```json { "resumed": [{ "id": "aut_…", "name": "After checkout" }] } ``` An event can do all three — starting one flow, ending another and waking a third — which is exactly what `order.placed` does. `matched: 0` means nothing was listening — no automation is switched on for that name. The event is still recorded. ::: warning An address nobody knows is skipped, not added An event carrying an email is not that person asking for mail. Without `consent_source` an unknown address comes back as `skipped`. With it they are added to the automation's list first — the same consent record the [subscribe](/guide/campaigns#the-signup-page) endpoint requires — and the flow starts. On a double opt-in list they are added as *pending* and nothing runs until they confirm. ::: `fields` are merged, not replaced: an event about one thing does not wipe what is already known about that person. ## List the event names ``` GET /api/v1/events ``` Scope: `events:read` ```json { "data": [ { "id": "evt_…", "name": "trial.ended", "description": "Posted by the billing worker the night a free trial runs out", "declared": true, "seen_count": 412, "last_seen_at": "2026-09-23T09:58:02.000Z", "automations": 2, "live_automations": 1 } ] } ``` `declared` is `false` for a name that arrived from the API before anybody wrote it down under **Campaigns → Events**. Those are worth looking at: a mistyped event name is otherwise invisible, and it looks exactly like nothing having happened. --- # Webhooks Source: https://mailroom-docs.shahriyar.dev/api/webhooks # Webhooks Managing endpoints and reading their history. For what the events *are* and how to check a signature, see [Webhooks](/webhooks/). ## List endpoints ``` GET /api/v1/webhooks ``` Scope: `webhooks:read` ```json { "object": "webhook", "id": "whk_…", "url": "https://api.example.com/hooks/mail", "description": "Production receiver", "events": ["mail.received", "email.bounced"], "enabled": true, "mailbox_id": null, "domain_id": null, "last_status": 200, "last_delivered_at": "2026-09-21T09:58:02.000Z", "last_error_at": null, "last_error": null, "consecutive_failures": 0, "created_at": "2026-08-01T12:00:00.000Z" } ``` The **secret is never returned on a read**. It is shown once, at creation, and once more if you rotate it. ## Create ``` POST /api/v1/webhooks ``` Scope: `webhooks:write` ```json { "url": "https://api.example.com/hooks/mail", "description": "Production receiver", "events": ["mail.received", "email.bounced"], "domain_id": "dom_…", "enabled": true } ``` | Field | | | --- | --- | | `url` | **required**. Must be `https` | | `events` | Event names, or `["*"]` for everything **including events added later**. Defaults to `["*"]` | | `mailbox_id` | Only fire for mail in this one mailbox | | `domain_id` | Only fire for mail on this domain — every address on it, including ones added later | | `description` | For your own reference | Give one of `mailbox_id` or `domain_id`, or neither. Both together is a `400`: two answers to "what does this hear about" is a rule nobody can read back off the endpoint. Returns `201` **with the signing secret**: ```json { "object": "webhook", "id": "whk_…", "secret": "whsec_…", "…": "…" } ``` ::: danger Store the secret now It is shown here and never again. An endpoint that does not check the signature will accept anything anybody posts at it. ::: ### Where an endpoint may point The URL must be `https`, and it must not resolve to a private address. Loopback and private ranges, link-local, and cloud metadata hosts like `169.254.169.254` are all refused. This is not decoration: Mailroom fetches the URL and stores the reply where the key holder can read it, so an unchecked URL would be a way to read whatever the container can reach — an internal admin page, a metadata service — from outside. `localhost` and `127.0.0.1` are allowed **off production**, because a local receiver is how one gets tried out. ### Scope Three widths, narrowest first: | Scope | Hears about | | --- | --- | | `mailbox_id` | That one address | | `domain_id` | Every address on that domain, including ones added later | | neither | The whole account | A domain is usually what you want when an account sends for more than one of them: one endpoint per domain, rather than one per mailbox plus another every time a mailbox is added. ### Reach applies An unscoped webhook hears about every address, and a domain-scoped one hears about every address on that domain. A key that reaches only part of the account cannot create either, and cannot widen an existing one, because either would be a way to receive mail the key cannot read. A key restricted to named domains **may** scope a webhook to one of those domains. A key restricted to named mailboxes may not scope to a domain at all — the domain covers addresses the key was not given. ## Change ``` PATCH /api/v1/webhooks/:id ``` Scope: `webhooks:write` ```json { "enabled": true, "events": ["*"], "rotate_secret": false } ``` Turning an endpoint **back on also clears its failure count**, since that is what somebody means by having fixed it. `rotate_secret: true` replaces the secret and returns the new one, once. ## Turn off or delete ``` DELETE /api/v1/webhooks/:id DELETE /api/v1/webhooks/:id?disable_only=true ``` Scope: `webhooks:write` `disable_only` stops delivery but keeps the endpoint and its history, which is usually what you want while something is being repaired. A plain delete takes the endpoint **and its deliveries** together. ## Test ``` POST /api/v1/webhooks/:id/ping ``` Scope: `webhooks:write` Sends a `webhook.test` event and **waits for the answer**. Unlike a real event it is not retried and not sent in the background: the point is to see, now, whether the endpoint is reachable and whether it is checking the signature. ```json { "object": "webhook_ping", "webhook_id": "whk_…", "succeeded": true, "status_code": 200, "duration_ms": 214, "response_body": "{\"ok\":true}", "error": null } ``` A failure comes back as `502` **with this same body**, not as a bare error — the call worked, the endpoint did not. ## Deliveries ``` GET /api/v1/webhook-deliveries ``` Scope: `webhooks:read` Every attempt at every endpoint, newest first, with the status and the reply that came back. | Filter | | | --- | --- | | `webhook_id` | One endpoint | | `event` | One event name | | `succeeded` | `true` or `false` | | `limit`, `cursor` | See [Pagination](/api/pagination) | ```json { "object": "webhook_delivery", "id": "whd_…", "webhook_id": "whk_…", "event": "mail.received", "payload": { "email": { "…": "…" } }, "attempt": 2, "status_code": 500, "response_body": "Internal Server Error", "error": "Endpoint replied 500", "duration_ms": 1204, "succeeded": false, "created_at": "2026-09-21T09:58:02.000Z" } ``` A delivery carries the payload of the event it was for, so it is only readable through a webhook this key may see. ## Replay ``` POST /api/v1/webhook-deliveries/:id/replay ``` Scope: `webhooks:write` Sends a stored payload again — what an endpoint that was down gets caught up with, once it is back. ```sh # Everything that failed in the last hour, again. curl -s "$BASE/webhook-deliveries?succeeded=false&limit=100" -H "Authorization: Bearer $KEY" \ | jq -r '.data[].id' \ | xargs -I{} curl -s -X POST "$BASE/webhook-deliveries/{}/replay" -H "Authorization: Bearer $KEY" ``` Same reply shape as a ping, and the same `502`-with-a-body on failure. --- # Statistics Source: https://mailroom-docs.shahriyar.dev/api/stats # Statistics How much was sent and received, and how it landed. ``` GET /api/v1/stats ``` Scope: `stats:read` | Parameter | | | --- | --- | | `days` | A window ending now. 1 to 365. **30** by default | | `since`, `until` | An explicit window. `since` overrides `days` | | `mailbox_id`, `mailbox`, `domain` | Narrow to part of the account | ```sh curl "https://mail.yourdomain.com/api/v1/stats?days=7" \ -H "Authorization: Bearer mk_live_..." ``` ```json { "object": "stats", "since": "2026-09-14T10:00:00.000Z", "until": "2026-09-21T10:00:00.000Z", "sending": { "sent": 1284, "delivered": 1249, "bounced": 21, "complained": 1, "failed": 3, "opened": 611, "total_opens": 903, "bounce_rate": 1.64, "complaint_rate": 0.08, "open_rate": 47.59 }, "receiving": { "received": 312, "threads": 189, "unread": 7 }, "drafts": 4, "bytes": 48123904, "days": [ { "day": "2026-09-14", "sent": 180, "received": 44, "delivered": 176, "bounced": 3, "opened": 84 } ], "mailboxes": [ { "id": "mbx_…", "address": "receipts@example.com", "sent": 1102, "received": 0 } ] } ``` ## The rates `bounce_rate`, `complaint_rate` and `open_rate` are **shares of sent mail out of 100** — so `1.64` is 1.64%, not 164%. | | SES starts warning above | | --- | --- | | `bounce_rate` | **5** | | `complaint_rate` | **0.1** | Watching these two is the single most useful thing this endpoint is for. A bounce rate climbing past 3 is worth investigating before AWS does it for you. `open_rate` counts messages whose tracking image was loaded. Apple Mail and Gmail fetch images through their own servers, so treat it as evidence of delivery rather than proof of reading. ## Days `days` has a row for **every day in the window**, quiet ones included, so a chart needs one call rather than one point per request. Days are UTC. ## Mailboxes Up to 50 mailboxes, busiest first. `received` is always 0 for a send-only address, which makes it easy to see which mailboxes are doing what. ## Receiving `receiving.threads` and `receiving.unread` are **not** limited to the window — they are the current state of the inbox, because "how many unread do I have over the last 30 days" is not a question anybody asks. --- # Getting started Source: https://mailroom-docs.shahriyar.dev/sdk/ # The Node SDK ```sh npm install @shahriyardx/mailroom ``` The whole API, typed, with **no dependencies** — one `fetch` and Web Crypto. Node 18 or newer, and anywhere else `fetch` exists: Workers, Deno, Bun, the browser. Ships ESM, CommonJS and types. [npm](https://www.npmjs.com/package/@shahriyardx/mailroom) · [source](https://github.com/shahriyardx/mailroom/tree/main/packages/sdk) ## Start ```ts import { Mailroom } from "@shahriyardx/mailroom"; const mail = new Mailroom({ apiKey: process.env.MAILROOM_API_KEY, baseUrl: "https://mail.yourdomain.com", }); const me = await mail.me(); console.log(me.name, me.scopes, me.reach); await mail.emails.send({ from: "receipts@yourdomain.com", to: "customer@example.net", subject: "Your receipt", html: "

Thanks.

", }); ``` CommonJS is the same: ```js const { Mailroom } = require("@shahriyardx/mailroom"); ``` ## Settings ```ts const mail = new Mailroom({ apiKey: process.env.MAILROOM_API_KEY, // default: process.env.MAILROOM_API_KEY baseUrl: "https://mail.yourdomain.com", // default: process.env.MAILROOM_BASE_URL timeout: 30_000, // ms to wait for a reply maxRetries: 2, // extra tries after a 429, 5xx or dropped socket headers: { "X-Trace-Id": "…" }, // sent on every call fetch: myFetch, // your own fetch, for tests or a proxy agent }); ``` With `MAILROOM_API_KEY` and `MAILROOM_BASE_URL` set, `new Mailroom()` on its own is enough. `baseUrl` is your instance's address. The `/api/v1` suffix is added for you, so `https://mail.yourdomain.com` and `https://mail.yourdomain.com/api/v1` both work. Both settings are checked in the constructor, so a missing key is an error where you made the client, not a `401` somewhere later. ## What is on the client | | | | --- | --- | | `mail.me()` | What this key is and what it may do | | `mail.emails` | [Sending](/sdk/sending), and reading what was sent | | `mail.threads` | [Conversations](/sdk/reading) | | `mail.messages` | Individual messages | | `mail.attachments` | Files on a message | | `mail.mailboxes` | [Addresses](/sdk/managing) | | `mail.domains` | Sending domains and their DNS | | `mail.labels` | Labels | | `mail.contacts` | Everyone corresponded with | | `mail.suppressions` | Blocked addresses | | `mail.webhooks` | Endpoints and their deliveries | | `mail.stats` | Sending and receiving numbers | | `mail.rateLimit` | The window from the last reply | | `mail.http` | The escape hatch, for an endpoint not yet wrapped | ## Webhooks The package also verifies incoming webhooks, with no Node build needed: ```ts import { constructWebhookEvent } from "@shahriyardx/mailroom"; const event = await constructWebhookEvent({ secret: process.env.MAILROOM_WEBHOOK_SECRET!, payload: rawBody, signature: request.headers.get("x-mailroom-signature"), }); ``` See [Verifying a call](/webhooks/verifying). ## Types Every object, parameter and event is exported: ```ts import type { Message, Thread, Mailbox, Domain, Label, Contact, Suppression, Webhook, WebhookDelivery, Stats, Page, SendEmailInput, ListThreadsParams, MailroomWebhookEvent, } from "@shahriyardx/mailroom"; ``` Timestamps are ISO 8601 **strings**, because that is what JSON carries. Pass one to `new Date()` when you need a date. --- # Sending Source: https://mailroom-docs.shahriyar.dev/sdk/sending # Sending ## One message ```ts const sent = await mail.emails.send({ from: "Support ", to: ["a@example.net", "b@example.net"], cc: "manager@example.net", bcc: "archive@yourdomain.com", reply_to: "noreply@yourdomain.com", subject: "Your order shipped", html: "

On its way

", text: "On its way", headers: { "X-Order-Id": "4821" }, }); console.log(sent.id, sent.ses_message_id, sent.thread_id); ``` `to`, `cc` and `bcc` take a string or an array, and `Name
` is understood. `from` has to be an address on a verified domain. A key that reaches a whole domain can use any address on it — the mailbox is created the first time it does. ## When it does not go out at once ```ts const sent = await mail.emails.send({ /* … */ }); if (sent.status === "queued") { // SES could not take it right now. It is in the queue and will keep trying. } ``` A send SES refuses for good throws. Anything else — throttling, an outage, a dropped socket — comes back `queued`, and the [send queue](/guide/queue) carries it from there. You do not have to do anything about it. ## Sending later ```ts const sent = await mail.emails.send({ from: "reminders@yourdomain.com", to: "customer@example.net", subject: "Your appointment tomorrow", text: "See you at 10.", scheduled_at: "in 2 hours", }); console.log(sent.status); // "scheduled" console.log(sent.scheduled_at); // "2026-09-21T16:00:00.000Z" ``` `scheduled_at` takes a `Date`, an ISO 8601 string, a Unix time, or a short relative form: `"in 30 minutes"`, `"in 2 hours"`, `"in 1 day"`. A time already past sends now, and 30 days is as far ahead as it goes. While it waits: ```ts await mail.emails.reschedule(sent.id, new Date("2026-10-01T09:00:00Z")); await mail.emails.cancel(sent.id); ``` Both throw `ConflictError` once the message has been picked up for sending. They work on a `queued` message too, not only a scheduled one. ## Templates ```ts const receipt = await mail.templates.create({ name: "Receipt", subject: "Your receipt, {{ name }}", html: "

Hello {{ name }}, you paid {{ amount }}.

", }); await mail.emails.send({ from: "receipts@yourdomain.com", to: "customer@example.net", template: receipt.id, data: { name: "Ada", amount: "£10.00" }, }); ``` {{ name }} substitutes with HTML escaped, {{{ body }}} substitutes without, and {{ user.name }} reaches into an object. That is the whole language — see [Templates](/api/templates). A value you did not send throws `ValidationError` naming what is missing, rather than leaving a hole in the message. `templates.get()` tells you what a template asks for: ```ts const template = await mail.templates.get(receipt.id); console.log(template.variables); // ["name", "amount"] ``` ## Attachments ```ts import { readFile } from "node:fs/promises"; const pdf = await readFile("invoice.pdf"); await mail.emails.send({ from: "receipts@yourdomain.com", to: "customer@example.net", subject: "Your invoice", html: '

Attached.

', attachments: [ { filename: "invoice.pdf", content: pdf.toString("base64"), content_type: "application/pdf", }, { filename: "logo.png", content: logoBase64, content_id: "logo", // embeds it, rather than attaching it }, ], }); ``` At most **20 files**, and 30 MB for the whole request. Base64 adds about a third, so that is roughly 22 MB of actual file. ## Sending exactly once ```ts await mail.emails.send( { from: "receipts@yourdomain.com", to: "a@b.c", subject: "Receipt #4821" }, { idempotencyKey: "receipt-4821" }, ); ``` Repeat the call with the same key and you get the first reply back, not a second message. Keys last 24 hours. Use something **meaningful** — `receipt-4821`, not a UUID made at call time. A fresh UUID on a retry is a different key and protects nothing. It also switches automatic retries on for that call, since repeating it is now safe. ## Many at once ```ts const result = await mail.emails.sendBatch([ { from: "news@yourdomain.com", to: "a@example.net", subject: "Hi", text: "…" }, { from: "news@yourdomain.com", to: "b@example.net", subject: "Hi", text: "…" }, ]); console.log(`${result.sent} sent, ${result.failed} failed`); for (const item of result.data) { if (!item.ok) console.error(`#${item.index}:`, item.error); } ``` Up to **100**. Every one is attempted, so one bad address does not throw the rest away. This does **not** throw when some fail — check `result.failed`. ## Replying to a conversation ```ts await mail.threads.reply(threadId, { text: "Refunded — sorry for the trouble.", reply_all: true, }); ``` Recipients, subject and the headers that keep it threaded come off the last message. See [Reading mail](/sdk/reading#replying). ## What was sent ```ts const page = await mail.emails.list({ status: ["bounced", "complained"], since: new Date(Date.now() - 7 * 24 * 3600 * 1000), limit: 50, }); for (const message of page.data) { console.log(message.to[0]?.address, message.status, message.error); } ``` A `Date` is serialised for you. So is an array — `status` goes out comma-separated. ## One send in full ```ts const detail = await mail.emails.get(sent.id); console.log(detail.status); // "delivered" | "bounced" | … console.log(detail.opened_at); // when the tracking image loaded, or null console.log(detail.events); // every SES event seen for it ``` The SES message id works here too, which is what a bounce report or a webhook hands you. ## A worked example Receipts, with a per-order idempotency key and bounces logged: ```ts import { Mailroom, isMailroomError } from "@shahriyardx/mailroom"; const mail = new Mailroom(); export async function sendReceipt(order: Order) { try { return await mail.emails.send( { from: "Receipts ", to: order.customerEmail, subject: `Receipt for order ${order.id}`, html: receiptHtml(order), headers: { "X-Order-Id": String(order.id) }, }, { idempotencyKey: `receipt-${order.id}` }, ); } catch (error) { if (isMailroomError(error) && error.code === "invalid_request") { // A bad address is the order's problem, not something to retry. await flagBadEmail(order.id, error.message); return null; } throw error; } } ``` --- # Reading mail Source: https://mailroom-docs.shahriyar.dev/sdk/reading # Reading mail Inbound mail lives in **threads**. A thread is the conversation; a message is one item in it. ## The inbox ```ts const inbox = await mail.threads.list({ folder: "inbox", unread: true, limit: 20, }); for (const thread of inbox.data) { console.log(thread.subject, thread.unread_count, thread.participants); } ``` Filters: `folder`, `label` or `label_id`, `q`, `unread`, `starred`, `has_attachments`, `participant`, `subject`, `since`, `until`, and `mailbox_id` / `mailbox` / `domain` to narrow to part of the account. ## Paging `listAll` holds the cursor for you: ```ts for await (const thread of mail.threads.listAll({ folder: "inbox" })) { console.log(thread.subject); if (enough) break; // stopping early stops fetching } ``` It is on `emails`, `threads`, `messages`, `contacts`, `suppressions`, and as `webhooks.listAllDeliveries`. Or hold it yourself: ```ts let cursor: string | undefined; do { const page = await mail.threads.list({ cursor, limit: 100 }); await handle(page.data); cursor = page.next_cursor ?? undefined; } while (cursor); ``` ## One conversation ```ts const thread = await mail.threads.get(id); for (const message of thread.messages ?? []) { console.log(message.from.address, message.subject); console.log(message.text ?? message.html); } ``` Pass `{ includeBody: false }` for a lighter reply when only the shape matters. ## Filing ```ts await mail.threads.update(id, { folder: "archive", is_read: true, add_labels: ["Refunds"], // by name or by id remove_labels: ["Needs reply"], }); ``` Only what you send is changed. An unknown label is a `ValidationError` and **nothing is changed** — labels are resolved before anything is written, so you never get an error next to a move that already happened. ```ts // To the trash, and out of it for good on a second call. await mail.threads.delete(id); await mail.threads.delete(id, { permanent: true }); ``` ## Replying ```ts await mail.threads.reply(id, { text: "Thanks — sorted.", reply_all: true, quote: true, // on by default }); ``` | Field | | | --- | --- | | `text`, `html` | One is required | | `reply_all` | Also answer everyone else on the last message | | `to`, `cc`, `bcc` | Replace the worked-out recipients | | `subject` | Defaults to `Re: …` | | `quote` | Append the message being answered. On by default | | `attachments` | As on a normal send | ## Messages on their own ```ts const unread = await mail.messages.list({ direction: "inbound", unread: true, include_body: true, }); await mail.messages.update(id, { is_read: true, is_starred: true }); ``` Bodies are left out of a list unless you ask, because fifty of them is mostly HTML you did not want. ## The original message ```ts import { writeFile } from "node:fs/promises"; const eml = await mail.messages.raw(id); // Uint8Array of message/rfc822 await writeFile("message.eml", eml); ``` Only inbound mail has one. Outbound is assembled at send time and its wire form is not stored. ## Attachments ```ts const file = await mail.attachments.get(attachmentId); console.log(file.filename, file.size_bytes); console.log(file.download_url); // signed, good for 5 minutes // Or the bytes, in one call: const bytes = await mail.attachments.download(attachmentId); ``` Use `download_url` for anything large or headed to a browser — it goes straight to storage and does not spend your rate limit. ## A worked example An agent that answers unread support mail and files it: ```ts import { Mailroom } from "@shahriyardx/mailroom"; const mail = new Mailroom(); for await (const thread of mail.threads.listAll({ mailbox: "support@yourdomain.com", folder: "inbox", unread: true, })) { const full = await mail.threads.get(thread.id); const last = full.messages?.at(-1); if (!last || last.direction === "outbound") continue; const answer = await draftReply(last.text ?? ""); if (!answer) continue; await mail.threads.reply(thread.id, { text: answer }); await mail.threads.update(thread.id, { is_read: true, folder: "archive", add_labels: ["Answered"], }); } ``` --- # Managing the account Source: https://mailroom-docs.shahriyar.dev/sdk/managing # Managing the account ## Mailboxes ```ts const boxes = await mail.mailboxes.list(); const box = await mail.mailboxes.get(id); await mail.mailboxes.create({ address: "billing@yourdomain.com", display_name: "Billing", signature: "— Accounts", }); await mail.mailboxes.update(id, { signature: null }); // null clears it ``` The address cannot change. Make a new mailbox instead. ```ts // Deletes the mail in it too, so the flag is required. await mail.mailboxes.delete(id, { confirm: true }); ``` Without `confirm` the API returns `409` and the SDK throws a `ConflictError`. ## Domains ```ts const domain = await mail.domains.create("example.com"); for (const record of domain.records) { console.log(record.kind, record.name, "→", record.value, `(${record.purpose})`); } ``` Only a key that reaches the whole account may add a domain. Poll until it is ready: ```ts async function waitForDomain(name: string) { for (let attempt = 0; attempt < 40; attempt += 1) { const checked = await mail.domains.verify(name); if (checked.sending_enabled) return checked; await new Promise((resolve) => setTimeout(resolve, 30_000)); } throw new Error(`${name} did not verify in 20 minutes`); } ``` `get`, `verify` and `delete` all take the **name** as well as the id. ```ts await mail.domains.delete("example.com"); // here only await mail.domains.delete("example.com", { deleteInSes: true }); // and in SES ``` Deleting in SES cannot be undone, and other applications on the same AWS account may be relying on that identity. ## Labels ```ts const label = await mail.labels.create({ name: "Refunds", color: "#64748b" }); await mail.labels.update("Refunds", { color: "#0ea5e9" }); // by name works await mail.labels.delete(label.id); // threads stay ``` Put one on a thread through the thread: ```ts await mail.threads.update(threadId, { add_labels: ["Refunds"] }); ``` ## Contacts ```ts for await (const person of mail.contacts.listAll({ order: "frequent" })) { console.log(person.address, person.message_count); } ``` Only a key that reaches the whole account can read these — contacts are kept per account, so there is no honest way to narrow them. ## Blocked addresses ```ts const blocked = await mail.suppressions.list({ q: "example.net" }); await mail.suppressions.create({ address: "unsubscribed@example.net", reason: "Asked to stop", }); await mail.suppressions.delete("unsubscribed@example.net"); // id or address ``` Blocking an already-blocked address is not an error. Unblocking one that hard bounced risks your sending reputation — see [Blocked addresses](/api/suppressions). ## Webhooks ```ts const hook = await mail.webhooks.create({ url: "https://api.example.com/hooks/mail", events: ["mail.received", "email.bounced"], description: "Production receiver", }); console.log(hook.secret); // shown once. Store it now. ``` An endpoint hears about the whole account unless it is scoped. Pass `domain_id` for every address on one domain (including ones added later), or `mailbox_id` for a single address. One or the other, never both. ```ts await mail.webhooks.create({ url: "https://api.example.com/hooks/acme", events: ["*"], domain_id: "dom_…", // everything sent from or to @acme.com }); ``` ```ts await mail.webhooks.update(id, { enabled: true }); // also clears failures await mail.webhooks.update(id, { rotate_secret: true }); // new secret, once await mail.webhooks.disable(id); // keep the history await mail.webhooks.delete(id); // endpoint and history const ping = await mail.webhooks.ping(id); console.log(ping.succeeded, ping.status_code, ping.response_body); ``` A failed ping is a **result**, not a throw — the call worked, the endpoint did not. Catch an endpoint up after an outage: ```ts for await (const delivery of mail.webhooks.listAllDeliveries({ succeeded: false })) { await mail.webhooks.replay(delivery.id); } ``` ## Statistics ```ts const stats = await mail.stats.get({ days: 30 }); if (stats.sending.bounce_rate > 3) { await alert(`Bounce rate at ${stats.sending.bounce_rate}%`); } for (const day of stats.days) { console.log(day.day, day.sent, day.delivered, day.bounced); } ``` `days` has a row for every day in the window, quiet ones included. Rates are shares out of 100 — SES warns above **5** bounces and **0.1** complaints. ## An endpoint not yet wrapped ```ts const custom = await mail.http.request<{ ok: boolean }>({ method: "POST", path: "/some/new/endpoint", query: { limit: 10 }, body: { hello: "world" }, }); ``` The key, base URL, timeout, retries and error mapping all still apply. --- # Errors and retries Source: https://mailroom-docs.shahriyar.dev/sdk/errors # Errors and retries Anything other than a `2xx` throws. Every error extends `MailroomError` and carries `status`, `code`, `message` and the decoded `body`. ```ts import { isMailroomError, MailroomError, NotFoundError, RateLimitError, ValidationError, } from "@shahriyardx/mailroom"; try { await mail.emails.send({ from: "nobody@unverified.example", to: "a@b.c" }); } catch (error) { if (error instanceof RateLimitError) { await sleep((error.retryAfter ?? 5) * 1000); } else if (error instanceof ValidationError) { console.error("bad field:", error.param, error.message); } else if (error instanceof NotFoundError) { // gone, or outside this key's reach — the two look the same on purpose } else if (isMailroomError(error)) { console.error(error.code, error.status, error.message); } else { throw error; // not ours } } ``` ## The classes | Class | Status | `code` | Usually means | | --- | --- | --- | --- | | `AuthenticationError` | 401 | `unauthorized` | Key missing, mistyped or revoked | | `PermissionError` | 403 | `forbidden` | Missing a scope, or outside the key's reach | | `NotFoundError` | 404 | `not_found` | No such object, or none this key may see | | `ConflictError` | 409 | `conflict` | Already exists, or needs a confirmation flag | | `PayloadTooLargeError` | 413 | `payload_too_large` | Over 30 MB. Usually an attachment | | `ValidationError` | 422 | `invalid_request` | A bad field; `param` names it | | `RateLimitError` | 429 | `rate_limited` | Too many calls; `retryAfter` in seconds | | `ServerError` | 5xx | `server_error` | The instance failed. Safe to retry | | `TimeoutError` | — | `timeout` | No reply within `timeout` | | `ConnectionError` | — | `connection_error` | DNS, TLS, a dropped socket | `PermissionError` also carries `requiredScope` when a missing scope was the reason: ```ts catch (error) { if (error instanceof PermissionError) { console.error(`This key needs ${error.requiredScope}`); } } ``` `WebhookVerificationError` is separate — it comes from `constructWebhookEvent`, not from a call. ## Retries The client retries on its own when repeating is **safe**: - Every `GET` - Any `POST` sent with an `idempotencyKey` Nothing else. An unkeyed send that times out is never repeated, because "probably did not send" is not good enough to risk sending twice. What is retried: `429`, any `5xx`, timeouts and dropped connections. Waits are exponential with jitter, and a `Retry-After` is obeyed when the server sends one. ```ts const mail = new Mailroom({ maxRetries: 4 }); // default 2; 0 turns it off ``` ## Rate limit headers ```ts await mail.me(); console.log(mail.rateLimit); // { limit: 300, remaining: 297, resetAt: 2026-09-21T10:01:49.000Z } ``` Kept from the most recent reply, and `null` before the first one. ## Timeouts and cancelling ```ts const mail = new Mailroom({ timeout: 10_000 }); ``` Pass your own signal per call, which is combined with the client's timeout: ```ts const controller = new AbortController(); setTimeout(() => controller.abort(), 2_000); await mail.threads.list({}, { signal: controller.signal }); ``` An abort you triggered throws **your** abort error. One from the client's own timer throws `TimeoutError`, so you can tell them apart. ## What does not throw Three things look like failures and are not: ```ts // A batch where some messages failed. Check result.failed. const result = await mail.emails.sendBatch(many); // A webhook endpoint that was unreachable. Check ping.succeeded. const ping = await mail.webhooks.ping(id); // The same for a replay. const replay = await mail.webhooks.replay(deliveryId); ``` In each case the call itself worked. Treating them as thrown errors would lose the detail you actually need. --- # Overview Source: https://mailroom-docs.shahriyar.dev/webhooks/ # Webhooks Being told what happens to mail, rather than asking. ## What arrives A `POST` with a JSON body, and three headers: | Header | | | --- | --- | | `X-Mailroom-Event` | The event name | | `X-Mailroom-Signature` | `t=,v1=` | | `X-Mailroom-Webhook-Id` | Which endpoint this came from | The body is always the same envelope: ```json { "id": "whd_9f2c…", "object": "event", "type": "mail.received", "created_at": "2026-09-21T09:58:02.000Z", "data": { "email": { "…": "…" } } } ``` `id` is also the **delivery id**, so a repeat — a retry after your endpoint timed out, or a replay you triggered — can be recognised and ignored. ## Setting one up Two ways, and they do the same thing: - **Settings → Webhooks** in the app - [`POST /api/v1/webhooks`](/api/webhooks#create) Either way the reply carries the **signing secret**, shown once and never again. ## What to do in a handler 1. Read the **raw body** as text. Not a parsed object. 2. [Verify the signature](/webhooks/verifying) against it. 3. Answer `2xx` **quickly** — do the slow part after, or on a queue. 4. Ignore an `id` you have already seen. A handler that takes ten seconds is a handler that gets retried, because the timeout is ten seconds. ## Next - [The events](/webhooks/events) — all nine, and what is in each - [Verifying a call](/webhooks/verifying) — with code that works - [Retries and replays](/webhooks/retries) — what happens when you are down --- # The events Source: https://mailroom-docs.shahriyar.dev/webhooks/events # The events Eleven, plus a test. Subscribe with a list of names, or `["*"]` for everything including events added later. | Event | When | | --- | --- | | `mail.received` | A message arrived in a mailbox | | `email.sent` | A message was handed to SES | | `email.delivered` | The receiving server accepted it | | `email.bounced` | It came back | | `email.complained` | Somebody marked it as spam | | `email.opened` | The tracking image was loaded | | `email.delayed` | SES is still trying | | `email.rejected` | SES refused to send it | | `email.failed` | It could not be handed to SES, and no attempts are left | | `email.canceled` | A scheduled message was called off before it went out | | `thread.updated` | A thread was moved, read, starred or labelled through the API | `webhook.test` is sent only by a [ping](/api/webhooks#test). It is deliberately **not** in the subscribable list, because sending a test under a real event name would have a receiver record something that never happened. ::: warning The email.* events need a configuration set Everything except `email.sent` comes from SES's own reporting. Without `SES_CONFIGURATION_SET` set, SES never reports, and those events never fire. See [Sending domains](/guide/domains#delivery-reporting). `email.sent` fires from the app itself the moment SES accepts a message, so it arrives either way, and so do `email.failed` and `email.canceled`, which are about this app's own [send queue](/guide/queue) rather than about SES. ::: ::: tip A test key produces them without sending anything A [test key](/guide/test-mode) fires `email.sent` and then a simulated delivery or bounce, in the same shape as the real thing with `simulated: true` added. It is the way to try a receiver end to end without a configuration set, and without bouncing a real message. ::: ## mail.received ```json { "id": "whd_…", "object": "event", "type": "mail.received", "created_at": "2026-09-21T09:58:02.000Z", "data": { "email": { "id": "msg_…", "thread_id": "thr_…", "mailbox_id": "mbx_…", "mailbox": "support@example.com", "message_id": "", "from": { "name": "Ada", "address": "ada@example.net" }, "to": [{ "name": null, "address": "support@example.com" }], "delivered_to": "support@example.com", "subject": "Refund for order 4821", "snippet": "Hi — I'd like to return…", "folder": "inbox", "has_attachments": true, "spf": "pass", "dkim": "pass", "dmarc": "pass", "spam_score": 0, "mailed_by": "us-west-2-amazonses.npmjs.com", "signed_by": "npmjs.com", "tls": "TLS1.3", "received_at": "2026-09-21T09:58:01.000Z" } } } ``` `delivered_to` is the address this copy actually arrived at, which differs from `mailbox` when a catch-all caught it. The body is **not** included — it can be megabytes. Fetch it with [`GET /messages/:id`](/api/messages#read-one) when you need it. ## email.sent ```json { "type": "email.sent", "data": { "email": { "id": "msg_…", "thread_id": "thr_…", "mailbox": "receipts@example.com", "ses_message_id": "0100018f…", "message_id": "<…@example.com>", "from": "receipts@example.com", "to": [{ "name": null, "address": "customer@example.net" }], "cc": [], "subject": "Your receipt", "status": "sent", "api_key_id": "key_…", "sent_at": "2026-09-21T09:58:00.000Z" } } } ``` `api_key_id` is set when the message came in through the API, so you can tell a script's mail from a person's. ## The delivery events `email.delivered`, `email.bounced`, `email.complained`, `email.opened`, `email.delayed` and `email.rejected` all carry the same shape: ```json { "type": "email.bounced", "data": { "email": { "id": "msg_…", "thread_id": "thr_…", "mailbox": "receipts@example.com", "ses_message_id": "0100018f…", "message_id": "<…@example.com>", "from": "receipts@example.com", "to": [{ "name": null, "address": "gone@example.net" }], "subject": "Your receipt", "status": "bounced" }, "recipients": ["gone@example.net"], "detail": "smtp; 550 5.1.1 user unknown", "occurred_at": "2026-09-21T09:58:40.000Z" } } ``` `recipients` is **which addresses this event was about** — a message to five people can bounce for one of them, and `to` still lists all five. A [test key](/guide/test-mode) produces the same shape with `"simulated": true` alongside `occurred_at`, and `"test": true` on the email. Nothing else differs, which is the point. ## email.failed and email.canceled Both are about this app's [send queue](/guide/queue) rather than about SES. `email.failed` fires when a message could not be handed to SES and the attempts have run out. It carries the same `email` object as `email.sent`, plus the last reason: ```json { "type": "email.failed", "data": { "email": { "id": "msg_…", "status": "failed", "…": "…" }, "error": "Maximum sending rate exceeded" } } ``` `email.canceled` fires when a scheduled or queued message is called off with [`POST /emails/:id/cancel`](/api/emails#call-one-off), and carries the `email` object alone. ## thread.updated Fires when a thread is changed through [`PATCH /threads/:id`](/api/threads#change-one) — not when it changes in the web app, and not when a new message arrives. ```json { "type": "thread.updated", "data": { "thread": { "object": "thread", "id": "thr_…", "folders": ["archive"], "…": "…" } } } ``` `data.thread` is the full thread object as it now is. ## Which endpoints hear what | The endpoint | Hears | | --- | --- | | No `mailbox_id` | Every event on the account | | A `mailbox_id` | Only events for that mailbox | An event with no mailbox of its own reaches every endpoint that has no `mailbox_id`. --- # Verifying a call Source: https://mailroom-docs.shahriyar.dev/webhooks/verifying # Verifying a call Your endpoint is a public URL. Anybody can post to it. The signature is what separates a real event from a stranger's. ## The scheme ``` X-Mailroom-Signature: t=1758448682,v1=4a8f3c… ``` `v1` is `HMAC-SHA256(secret, ".")`, hex. To check it: 1. Split `t` and `v1` out of the header. 2. Reject if `t` is more than **300 seconds** from now. That is what stops an old call being replayed at you. 3. Recompute the HMAC over `` `${t}.${rawBody}` ``. 4. Compare in **constant time**. ::: danger Verify the raw body `JSON.parse` followed by `JSON.stringify` does not always give back the same bytes — key order, number formatting, escapes. The signature is over bytes. Read the body as text or a buffer, verify, **then** parse. ::: ## With the SDK `constructWebhookEvent` does all four steps and throws if anything is wrong, so a handler that forgets to check a return value still cannot be fooled. ::: code-group ```ts [Next.js] import { constructWebhookEvent } from "@shahriyardx/mailroom"; export async function POST(request: Request) { const raw = await request.text(); try { const event = await constructWebhookEvent({ secret: process.env.MAILROOM_WEBHOOK_SECRET!, payload: raw, signature: request.headers.get("x-mailroom-signature"), }); switch (event.type) { case "mail.received": await queue.add("new-mail", { id: event.data.email.id }); break; case "email.bounced": console.warn("bounced", event.data.recipients, event.data.detail); break; } return Response.json({ ok: true }); } catch { return new Response("bad signature", { status: 400 }); } } ``` ```js [Express] const express = require("express"); const { constructWebhookEvent } = require("@shahriyardx/mailroom"); const app = express(); app.post( "/hooks/mail", express.raw({ type: "application/json" }), // not express.json() async (req, res) => { try { const event = await constructWebhookEvent({ secret: process.env.MAILROOM_WEBHOOK_SECRET, payload: req.body, signature: req.get("x-mailroom-signature"), }); res.json({ ok: true }); await handle(event); } catch { res.status(400).send("bad signature"); } }, ); ``` ```ts [Hono / Workers] import { Hono } from "hono"; import { constructWebhookEvent } from "@shahriyardx/mailroom"; const app = new Hono<{ Bindings: { MAILROOM_WEBHOOK_SECRET: string } }>(); app.post("/hooks/mail", async (c) => { const raw = await c.req.text(); try { const event = await constructWebhookEvent({ secret: c.env.MAILROOM_WEBHOOK_SECRET, payload: raw, signature: c.req.header("x-mailroom-signature"), }); return c.json({ ok: true, type: event.type }); } catch { return c.text("bad signature", 400); } }); ``` ::: `verifyWebhook` is the same check as a plain boolean if you would rather parse the body yourself. ## Without the SDK ::: code-group ```js [Node] const { createHmac, timingSafeEqual } = require("node:crypto"); function verify(secret, rawBody, header, tolerance = 300) { const parts = Object.fromEntries( header.split(",").map((piece) => { const at = piece.indexOf("="); return [piece.slice(0, at).trim(), piece.slice(at + 1).trim()]; }), ); const timestamp = Number(parts.t); if (!Number.isFinite(timestamp)) return false; if (Math.abs(Date.now() / 1000 - timestamp) > tolerance) return false; const expected = createHmac("sha256", secret) .update(`${timestamp}.${rawBody}`) .digest("hex"); const left = Buffer.from(expected, "utf8"); const right = Buffer.from(parts.v1 ?? "", "utf8"); return left.length === right.length && timingSafeEqual(left, right); } ``` ```python [Python] import hmac, hashlib, time def verify(secret: str, raw_body: bytes, header: str, tolerance: int = 300) -> bool: parts = dict( piece.strip().split("=", 1) for piece in header.split(",") if "=" in piece ) try: timestamp = int(parts["t"]) except (KeyError, ValueError): return False if abs(time.time() - timestamp) > tolerance: return False expected = hmac.new( secret.encode(), f"{timestamp}.".encode() + raw_body, hashlib.sha256, ).hexdigest() return hmac.compare_digest(expected, parts.get("v1", "")) ``` ```go [Go] func Verify(secret, rawBody, header string, tolerance time.Duration) bool { var ts int64 var got string for _, piece := range strings.Split(header, ",") { name, value, ok := strings.Cut(strings.TrimSpace(piece), "=") if !ok { continue } switch name { case "t": ts, _ = strconv.ParseInt(value, 10, 64) case "v1": got = value } } if ts == 0 { return false } if d := time.Since(time.Unix(ts, 0)); d > tolerance || d < -tolerance { return false } mac := hmac.New(sha256.New, []byte(secret)) fmt.Fprintf(mac, "%d.%s", ts, rawBody) want := hex.EncodeToString(mac.Sum(nil)) return hmac.Equal([]byte(want), []byte(got)) } ``` ::: ## Testing your handler Sign a body yourself and post it, rather than waiting for real mail: ```ts import { signWebhookPayload } from "@shahriyardx/mailroom"; const body = JSON.stringify({ id: "whd_test", object: "event", type: "mail.received", created_at: new Date().toISOString(), data: { email: { id: "msg_test", subject: "Hello" } }, }); await fetch("http://localhost:3000/hooks/mail", { method: "POST", headers: { "Content-Type": "application/json", "X-Mailroom-Signature": await signWebhookPayload("whsec_…", body), }, body, }); ``` Or point a real endpoint at a tunnel and use [ping](/api/webhooks#test), which tells you the status and the reply your handler gave. ## Rotating a secret ```sh curl -X PATCH https://mail.yourdomain.com/api/v1/webhooks/whk_… \ -H "Authorization: Bearer $KEY" \ -H "Content-Type: application/json" \ -d '{ "rotate_secret": true }' ``` The new secret is in the reply, once. There is no overlap window: deploy the new secret to your handler first if you cannot afford a gap, or accept a few seconds of rejected calls, which will be retried anyway. --- # Retries and replays Source: https://mailroom-docs.shahriyar.dev/webhooks/retries # Retries and replays ## What happens when you are down Each event is attempted up to **four times**, spread over about forty seconds: | Attempt | Waits | | --- | --- | | 1 | immediately | | 2 | 2 seconds | | 3 | 10 seconds | | 4 | 30 seconds | Each attempt has a **10-second timeout**. A handler slower than that is a handler that gets retried, so answer quickly and do the work afterwards. Every attempt is written down, whether it worked or not, and you can read them back from [`GET /webhook-deliveries`](/api/webhooks#deliveries). ## What counts as failure | Your reply | | | --- | --- | | `2xx` | Success. No more attempts | | `408` or `429` | Retried | | Any other `4xx` | **Given up on immediately** | | `5xx` | Retried | | No reply, or a timeout | Retried | A `4xx` other than those two means your endpoint understood the call and said no. Repeating it will not change the answer, so it is not repeated. ::: warning This includes 401 and 403 If your handler rejects a call because you got the secret wrong, Mailroom takes it at its word and gives up on that event. Fix the secret and [replay](#replaying) what you missed. ::: ## Being switched off After **20 failures in a row**, the endpoint is disabled. An endpoint that has been gone for a day should not still be collecting retries. Turn it back on when it is fixed: ```sh curl -X PATCH https://mail.yourdomain.com/api/v1/webhooks/whk_… \ -H "Authorization: Bearer $KEY" \ -H "Content-Type: application/json" \ -d '{ "enabled": true }' ``` Enabling also **clears the failure count**, since that is what somebody means by having fixed it. ## Duplicates are your job Delivery is at-least-once. A handler that times out after doing its work still gets retried, because Mailroom never heard the answer. The envelope's `id` is the delivery id and is stable across retries of the same event, so: ```ts if (await seen.has(event.id)) return Response.json({ ok: true }); await seen.add(event.id, { ttl: "7d" }); await handle(event); ``` A replay you trigger yourself reuses the original `id` too — which is usually what you want, because a replay is the same event, not a new one. ## Replaying ``` POST /api/v1/webhook-deliveries/:id/replay ``` Everything that failed, again: ```sh BASE=https://mail.yourdomain.com/api/v1 curl -s "$BASE/webhook-deliveries?succeeded=false&limit=100" \ -H "Authorization: Bearer $KEY" \ | jq -r '.data[].id' \ | while read -r id; do curl -s -X POST "$BASE/webhook-deliveries/$id/replay" \ -H "Authorization: Bearer $KEY" | jq -c '{id: .delivery_id, ok: .succeeded}' done ``` Deliveries are kept until the endpoint is deleted, so there is no window to race. ## Checking an endpoint is alive ``` POST /api/v1/webhooks/:id/ping ``` Sends a `webhook.test` event and waits. Not retried, not backgrounded — it tells you now whether the endpoint is reachable and whether it is checking the signature, and it hands back the status and the body your handler returned. ## Ordering There is none. Events are dispatched as they happen and retried independently, so `email.delivered` can arrive before `email.sent` if the first attempt at the latter failed. Order by what is in the payload — `occurred_at`, `sent_at`, `received_at` — rather than by arrival.