SPB Git

Repository Public

API.md 60.4 KB 713 lines markdown

1# SP Mail — REST API v123Base URL: `https://mail.spboucher.ai/api/v1` (dev: `http://localhost:8731/api/v1`).4Machine-readable contract: [`OPENAPI.yaml`](OPENAPI.yaml), also served at `GET /api/v1/openapi.json` and `/openapi.yaml`. It is generated from the same route registry that validates requests (`server/src/v1/registry.ts`); regenerate the file with `pnpm openapi`.56This document describes what is implemented and tested (`tests/integration/v1-*.test.ts`). Everything that is *not* supported is listed in [§14](#14-limits-and-what-is-not-supported). The session / JMAP-gateway contract of the web and native apps is unchanged and stays in `api-contract.md`.78Contents: [1 Conventions](#1-conventions) · [2 Authentication](#2-authentication) · [3 Scopes](#3-scopes) · [4 Address-level authorization](#4-address-level-authorization) · [5 Addresses and aliases](#5-addresses-and-aliases) · [6 Sending](#6-sending) · [7 Delivery status](#7-delivery-status-vocabulary) · [8 Reading](#8-reading-searching-synchronising) · [9 Modifying](#9-modifying-messages) · [10 Drafts and files](#10-drafts-and-files) · [11 Webhooks and events](#11-webhooks-and-events) · [12 Introspection](#12-introspection) · [13 Administration](#13-administration-session-only) · [14 Limits](#14-limits-and-what-is-not-supported) · [15 Errors](#15-error-codes)910---1112## 1. Conventions1314**JSON** in, JSON out (`Content-Type: application/json`), except file upload (raw bytes in) and attachment download (bytes out). Unknown body fields are rejected (`400 invalid_request`). JSON bodies are limited to 1 MB, 6 MB on the composing routes (`/messages/send`, `/messages/send-batch`, reply, forward, drafts).1516**Errors** always use one envelope, with the HTTP status carrying the class:1718```json19{ "error": { "code": "from_not_allowed", "message": "This caller is not allowed to send from that address", "details": { } } }20```2122`details` is optional (validation issues, limits, offending recipients…). Codes are listed in [§15](#15-error-codes). Unknown paths under `/api/v1/` answer JSON `404 not_found` (never the webmail page).2324**Request ids.** Every response carries `X-Request-Id: req_…`; quote it when reporting a problem.2526**Pagination.** List endpoints take `?limit=` (1–100, default 25) and `?cursor=` and answer2728```json29{ "data": [ … ], "next_cursor": "eyJ2IjoxLC…", "has_more": true }30```3132Cursors are opaque and stable (new mail arriving during a walk never produces duplicates or gaps in the pages that follow). A message cursor is bound to the query that produced it: reusing it with other filters answers `400 invalid_cursor`. `next_cursor` is `null` on the last page; there is no trailing empty page. A page may hold fewer than `limit` items while `has_more` is true (see §8.1).3334**Idempotency.** `POST` routes that create or send accept `Idempotency-Key: <1–200 printable ASCII chars>`:3536| Situation | Result |37|---|---|38| first request | processed; status and body are stored for 24 h |39| same key, same request (method, route, path/query parameters, body) | the stored status and body, plus `Idempotency-Replayed: true` |40| same key, different request | `409 idempotency_conflict` |41| same key while the first is still running | `409 idempotency_in_progress` |4243Deterministic refusals (4xx except 429) are stored and replayed too. Failures (5xx) and `429` are not stored: retry with the same key. Keys are scoped per caller (two keys may use the same value). Supported on: `/messages/send`, `/messages/send-batch`, `/messages/{id}/reply`, `/messages/{id}/forward`, `/drafts`, `/drafts/{id}/send`, `/folders`, `/addresses`, `/aliases`, `/webhooks`. Not supported on `/files` (raw upload).4445**Rate limits.** Per API key, fixed one-minute window (`rate_per_minute`, default 60). Every key-authenticated response carries `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` (Unix seconds). Over the limit: `429 rate_limited` with `Retry-After`. A second limit, `daily_send_limit` (default 200 messages per UTC day), applies to sending: `429 daily_send_limit_exceeded` with `details: {limit, used}`. There is also a global guard of 3 000 requests/minute per IP.4647**Ids** are opaque strings; never parse them. `msg_…` (message), `thr_…` (thread), `fld_…` (folder), `att_…` (attachment), `file_…` (uploaded file), `msg_out_…` (a send tracked by the API), `evt_…` (event). Address, key, webhook, delivery and approval ids are UUIDs. A message id encodes the mailbox and the server's message id; it is re-checked against the caller's rights on every call, so a guessed or forged id answers `404 not_found`, exactly like an unknown one.4849**Dates** are ISO 8601 UTC.5051---5253## 2. Authentication5455### API keys5657```58Authorization: Bearer spm_<prefix>_<secret>59```6061- `prefix` (10 chars) is public and shown in lists; `secret` is 256 random bits. Only the SHA-256 of the secret is stored. **The token is shown exactly once**, when the key is created or rotated.62- A key is checked on every request (no cache): a revoked or expired key fails at once with `401 key_revoked` / `401 key_expired`; a wrong token gives `401 invalid_api_key`.63- **Never put a token in a URL.** A request whose query string carries a `spm_…`/`spx_…` value is refused with `400 token_in_url`, whatever its headers.64- Key requests send no cookie and need no `Origin` / `X-SPMail` header. A request bearing `Authorization: Bearer spm_…` is never treated as a cookie request: a session cookie sent alongside is ignored.65- Keys are created by an administrator (`POST /api/admin/api-keys`, §13) or, on the node, by the operator CLI: `cli key-create <name> --scopes mail.send,mail.read --addresses a@d,b@d [--external allow|approval|deny] [--rate N] [--daily N] [--expires ISO] [--all-addresses]`, `cli key-revoke <key id | spm_prefix>`.6667**Explorer tokens** (`spx_…`) are minted by an administrator for one key (`POST /api/admin/api-keys/{id}/explorer-token`): 10 minutes, exactly that key's permissions, flagged `explorer` in `/me` and in the usage log. They let an API explorer call the API without ever displaying a stored secret.6869### Sessions (the owner's own tools)7071Every `/api/v1` route also accepts a web session (cookie) or a native session token, exactly as the rest of the backend: non-GET cookie requests need `Origin: <site>` and `X-SPMail: 1` (CSRF rules unchanged). A session acts with the user's own rights: all mail scopes on the mailboxes the user owns or has been granted ([§4](#4-address-level-authorization)), `mail.admin` if the user's role is `admin`. Sessions are not subject to the per-key limits nor to the external-send policy.7273### Re-authentication (sessions only)7475Sensitive session operations need a passkey assertion made within the last 5 minutes, bound to the current session and user; otherwise `403 reauth_required`.7677```78POST /api/reauth/options   {}                         → { challenge_id, options }      (WebAuthn request options, allowCredentials = the user's passkeys)79POST /api/reauth/verify    { challenge_id, response }  → { ok, reauth_at, valid_until }80```8182Operations that require it: create / update / rotate an API key, approve an external send, change the webhook internal allowlist, change mailbox grants, run retention now, rotate a webhook secret, delete an address or mailbox through `/api/v1`. Revoking a key, rejecting an approval and cancelling a scheduled message do **not** (they only reduce what can happen). These two routes use the legacy error envelope `{error, message}`.8384---8586## 3. Scopes8788`mail.admin` implies every other scope. Session callers hold every scope except `mail.admin` (administrators hold it too).8990| Scope | Allows |91|---|---|92| `mail.send` | send, reply, send a draft, batch; read the status of sends; scheduled messages |93| `mail.read` | list and read messages, threads, folders, incremental sync; read events |94| `mail.search` | use search filters (`from`, `to`, `subject`, `text`, `label`) |95| `mail.modify` | read/unread, star, labels, move, archive, trash, create folders |96| `mail.delete` | permanent deletion (also allows trash) |97| `mail.drafts` | create, list, read, update, discard drafts |98| `mail.attachments.read` | list and download attachments |99| `mail.attachments.write` | upload files and attach them |100| `mail.addresses.read` | list addresses and read mailbox automation |101| `mail.addresses.manage` | create / update / delete alias-type addresses, write automation |102| `mail.aliases.manage` | create / update / delete alias-type addresses |103| `mail.webhooks.manage` | manage the key's own webhooks, deliveries, replay |104| `mail.admin` | everything, plus: create / suspend / delete physical mailboxes, `protected`, raw Sieve, `all_addresses` |105106| Endpoint | Scope (any of) |107|---|---|108| `GET /health`, `GET /openapi.json`, `GET /openapi.yaml` | none (public) |109| `GET /me` | any authenticated caller |110| `GET /messages`, `GET /threads` | `mail.read` (no search filter) · `mail.search` (with `from`/`to`/`subject`/`text`/`label`; `/threads` then needs both) |111| `GET /messages/{id}`, `GET /threads/{id}`, `GET /messages/changes`, `GET /folders` | `mail.read` |112| `PATCH /messages/{id}`, `POST /messages/{id}/move`, `POST /folders` | `mail.modify` |113| `DELETE /messages/{id}` | `mail.modify` or `mail.delete`; `?permanent=true` needs `mail.delete` |114| `GET /messages/{id}/attachments[/{attachment_id}]` | `mail.attachments.read` |115| `POST /files` | `mail.attachments.write` |116| `POST /messages/send` | `mail.send` (`draft: true` → `mail.drafts`); with `attachments` also `mail.attachments.write` |117| `POST /messages/send-batch`, `POST /messages/{id}/reply`, `POST /drafts/{id}/send` | `mail.send` |118| `POST /messages/{id}/forward` | `mail.send` **and** `mail.read` |119| `GET /messages/outbound[/{id}]` | `mail.send` or `mail.read` |120| `GET /messages/scheduled`, `DELETE /messages/scheduled/{id}` | `mail.send` |121| `POST/GET /drafts`, `GET/PATCH/DELETE /drafts/{id}` | `mail.drafts` |122| `GET /addresses`, `GET /addresses/{id}`, `GET /aliases`, `GET /addresses/{id}/automation` | `mail.addresses.read` |123| `POST /addresses`, `PATCH/DELETE /addresses/{id}`, `POST /aliases`, `PATCH/DELETE /aliases/{id}` | `mail.addresses.manage` or `mail.aliases.manage` (mailbox kinds: `mail.admin`) |124| `PUT /addresses/{id}/automation` | `mail.addresses.manage` (`raw_sieve`: `mail.admin`) |125| `/webhooks…`, `POST /webhook-deliveries/{id}/replay` | `mail.webhooks.manage` |126| `GET /events` | `mail.read`, `mail.webhooks.manage` or `mail.send` |127128A missing scope answers `403 insufficient_scope` with `details.required`.129130---131132## 4. Address-level authorization133134A scope says *what* a key may do; its **address allowlist** (`address_ids`) says *for which addresses*. Both are checked on every operation, together with the state of the address. A key never has implicit access to "everything": with an empty allowlist it sees nothing. `all_addresses: true` exists only for keys holding `mail.admin`.135136**Terms.** A *mailbox* is a physical store (one mail-server account). Every usable address is an *address* row attached to exactly one mailbox: the mailbox's own *primary address* (kind `mailbox`/`shared`) or an alias-type address (kinds `alias`, `notification`, `send_only`, `receive_only`, `temporary`) that delivers into it.137138**Sending.** `from` must be an address of the allowlist, `active` (not suspended, not expired) and allowed to send (`can_send`, kind ≠ `receive_only`). Otherwise `403 from_not_allowed` (not in the allowlist — including addresses that do not exist), `403 address_inactive` or `403 address_cannot_send`. The mail server itself does not validate the header `From` against the authenticated account (verified: it delivers a foreign `From` unchanged), so SP Mail is the enforcement point: the `From` header is always built by the server from the address row, and callers cannot set `From`, `Sender` or `Return-Path` ([§6](#6-sending)).139140**Reading.** For each mailbox reachable through the allowlist the key gets one *view*:141142| The allowlist contains | View |143|---|---|144| the mailbox's primary address (active) | **full**: every message of the mailbox |145| only alias-type addresses of that mailbox | **restricted** to those addresses |146147In a restricted view a message is visible if and only if at least one of these is an allowed address:148- an envelope recipient recorded by the mail server at delivery (header `Delivered-To`, added by the server, not by the sender);149- an address in `To`, `Cc` or `Bcc`;150- the address in `From` (mail sent as that address).151152Everything else in the same physical mailbox is invisible: listing omits it, and a direct `GET /messages/{id}` answers `404`. A message delivered through a multi-destination alias (§5.4) carries the *member's* address in `Delivered-To`; it is matched through `To`/`Cc`. Folder counters are `null` in restricted views (they would reveal the volume of the whole mailbox). Modifying (`mail.modify`, `mail.delete`) follows the same visibility rule. Suspended or expired addresses are removed from a key's effective allowlist (`403 address_inactive` when named explicitly).153154Passing `?address=` narrows a request: the primary address means the whole mailbox (needs a full view), an alias means only that alias's mail. An address outside the allowlist answers `403 address_not_allowed`.155156**Sessions.** A user reads and sends for the mailboxes it owns (`mailboxes.user_id`) and for those shared with it through `mailbox_grants(user_id, mailbox_id, can_read, can_send)`: `can_read` gives a full view (and JMAP-gateway access, `/api/me` lists the mailbox with `access: "shared"`), `can_send` allows sending. A read-only grant cannot submit mail, neither through `/api/v1` (`403 from_not_allowed`) nor through the JMAP gateway (`403 send_not_granted`).157158**Managing addresses.** A key with `mail.addresses.manage` / `mail.aliases.manage` may create, update and delete alias-type addresses only in mailboxes whose primary address is in its allowlist (`403 address_not_allowed` otherwise). Anything that creates, suspends or deletes a physical mailbox, sets `protected`, or grants access needs `mail.admin` (`403 admin_required`). Session callers need the administrator role for every address mutation. **A newly created address is never added to any key's allowlist**: an administrator must add it (`PATCH /api/admin/api-keys/{id}`) before a key can use it. A send-only key can therefore never create itself a new identity.159160**Message content is data.** Nothing in the server interprets the content of a message as an instruction: no header, subject or body can change a scope, an allowlist or a policy.161162---163164## 5. Addresses and aliases165166### 5.1 The address object167168```json169{170  "id": "0d6f…", "address": "alerts@spboucher.ai", "kind": "alias",171  "mailbox": "notifications@spboucher.ai", "mailbox_id": "9a1c…",172  "display_name": "Alertes", "signature_text": "", "signature_html": "", "avatar": null,173  "can_send": true, "can_receive": true,174  "status": "active", "suspended_reason": null, "expired": false, "expires_at": null,175  "retention_days": null, "retention_trash_days": null, "retention_junk_days": null, "quota_bytes": null,176  "reply_policy": "reject", "protected": false, "extra_destinations": [],177  "inbound": "accept",178  "created_at": "2026-11-19T06:00:00.000Z", "updated_at": "2026-11-19T06:00:00.000Z"179}180```181182| Field | Meaning |183|---|---|184| `kind` | `mailbox` (physical), `shared` (physical, shared with other users — set automatically when grants exist), `alias`, `notification` (alias intended for notifications; same behaviour as `alias`), `send_only`, `receive_only`, `temporary` |185| `can_send` / `can_receive` | forced by `send_only` (true/false) and `receive_only` (false/true) |186| `status` | `active` or `suspended`; `suspended_reason` is `"expired"` when the expiry worker suspended it |187| `expires_at` | required for `temporary`; allowed on any alias-type address |188| `reply_policy` | what happens to incoming mail when the address does not receive (`can_receive` false or kind `send_only`): `reject` (default), `accept`, `discard` |189| `inbound` | read-only: what the mail server does **now** with mail for this address — `accept`, `reject` (SMTP 550) or `discard` (accepted, then dropped) |190| `protected` | never deletable nor destructively modifiable, by any API |191| `extra_destinations` | other local addresses that also receive mail sent to this alias |192| `avatar` | `data:image/(png|jpeg|webp);base64,…`, at most 90 kB, or null |193| `retention_*`, `quota_bytes` | physical mailboxes only (set on the primary address) |194195### 5.2 Enforcement is real196197A state change is applied on the mail server before the call returns; if the mail server refuses, the row is rolled back. Verified by tests against the real server:198199| State | Effect on the mail server | Effect in the API |200|---|---|---|201| alias-type, `inbound: accept` | account alias enabled | — |202| alias-type suspended / expired / `reject` | account alias **disabled** (kept, so the name stays reserved): senders get `550 5.1.1 Mailbox does not exist` | sending refused (`403 address_inactive`); removed from keys' allowlists |203| any address, `inbound: discard` | accepted by SMTP, then dropped by a server-managed block of the mailbox's Sieve script (`if envelope :is "to" "<address>" { discard; stop; }`) | — |204| physical mailbox suspended | account permissions `emailReceive` and `jmapEmailSubmissionCreate` disabled: senders get `550 5.5.0 This account is not authorized to receive email`; the mail server refuses submissions, including those of the webmail | sending refused |205| physical mailbox, `can_receive: false` + `reject` | `emailReceive` disabled | — |206| `receive_only` or `can_send: false` | — | sending refused (`403 address_cannot_send`) — enforced by `/api/v1` only |207| `quota_bytes` | account quota `maxDiskQuota` | — |208| `extra_destinations` non-empty | the address becomes a mail-server **mailing list** whose recipients are the mailbox and the extra destinations | — |209| `expires_at` reached | the API refuses the address immediately; the hourly expiry worker then suspends it on the mail server and emits `address.suspended` (`reason: "expired"`) | — |210211Sending identities are created on demand: the first send from an address creates its JMAP identity with the address's display name and signatures. An identity that already exists (for instance one edited in the webmail) is never rewritten by a send; it is aligned with the address only when `display_name` or the signatures are changed through this API. When the mail server does not recognise the address as belonging to the account (alias disabled for reception, or mailing list), the mailbox's own identity is used: the header `From` is still the address, but the SMTP envelope sender is the mailbox's primary address.212213### 5.3 Endpoints214215| | |216|---|---|217| `GET /addresses?kind=&mailbox=&status=` | addresses visible to the caller (key: its allowlist; administrator session: all) → `{data:[address]}` |218| `POST /addresses` | create (201). Alias kinds need `mailbox`; `mailbox`/`shared` create a mail account (`mail.admin`), owned by `user_id` or by the administrator who owns the key/session |219| `GET /addresses/{id}` | `{id}` is the UUID or the address itself |220| `PATCH /addresses/{id}` | any subset of: `display_name`, `signature_text`, `signature_html`, `avatar`, `can_send`, `can_receive`, `status`, `expires_at`, `retention_days`, `retention_trash_days`, `retention_junk_days`, `quota_bytes`, `reply_policy`, `extra_destinations`, `kind`, `protected` |221| `DELETE /addresses/{id}` | alias kinds: removed from the mail server. Mailbox kinds (`mail.admin`): **detached** by default (account and mail kept); `?purge=delete-all-mail` with body `{"confirm":"delete-all-mail"}` destroys the account and all its mail → `{ok:true, purged}` |222| `GET /aliases`, `POST /aliases`, `PATCH /aliases/{id}`, `DELETE /aliases/{id}` | the same, restricted to alias-type addresses (a mailbox id answers 404) |223| `GET /addresses/{id}/automation`, `PUT …` | filters, auto-reply, forwarding of a mailbox (§5.5) |224225```bash226curl -X POST $BASE/aliases -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{227  "address": "sales@spboucher.ai", "mailbox": "contact@spboucher.ai", "display_name": "Ventes" }'228# 201 → the address object (kind "alias", inbound "accept")229230curl -X PATCH $BASE/aliases/sales@spboucher.ai -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"status":"suspended"}'231# 200 → status "suspended", inbound "reject"   (mail to it now bounces with 550 5.1.1)232```233234Rules: the domain must be hosted (`400 unknown_domain`); the address must be free in SP Mail and on the mail server (`409 address_taken`); an alias cannot become a mailbox or the reverse (`400 kind_change_unsupported`); `temporary` needs `expires_at` (`400 expires_at_required`); quota and retention only on a primary address (`400 quota_mailbox_only`, `400 retention_mailbox_only`).235236**Protected addresses.** `info@` and `contact@spboucher.ai` (and `postmaster@`, `abuse@`, `dmarc@`; list in `SPMAIL_PROTECTED_ADDRESSES`) are protected. On a protected address, deletion and any change of `status`, `kind`, `can_receive`, `expires_at`, `retention_*`, `reply_policy` or `extra_destinations` answer `403 protected_address`; display name, signatures, avatar, `can_send` and quota remain editable. A mailbox that carries a protected address cannot be detached or purged, by `/api/v1` or by the legacy `/api/admin/mailboxes` routes; a protected alias cannot be removed by the legacy alias route. An administrator can set `protected: true`; it cannot be unset through any API.237238### 5.4 Multi-destination aliases239240`extra_destinations` lists other **local addresses known to SP Mail** (`400 invalid_destination` for anything else — no external forwarding through this field). Mail to the alias is then delivered to its mailbox and to each destination, by a mailing list on the mail server. The delivery status of a send to such an alias aggregates the members' statuses (§7).241242### 5.5 Automation (filters, auto-reply, forwarding)243244Per physical mailbox; `{id}` must be its primary address (`409 not_a_mailbox` otherwise) and the caller needs a full view of it.245246```json247PUT /addresses/contact@spboucher.ai/automation248{249  "rules": [ { "id": "r1", "name": "Factures", "enabled": true, "match": "all",250               "conditions": [ { "field": "subject", "op": "contains", "value": "facture" } ],251               "actions": [ { "type": "move", "folder": "Factures" }, { "type": "flag" } ] } ],252  "vacation": { "enabled": true, "subject": "Absent", "text": "De retour lundi.", "from": "2026-12-20", "to": "2027-01-04", "days": 3 },253  "forward": { "to": "simon@spboucher.ai", "keep_copy": true }254}255→ { "managed": true, "active": true, "rules": [...], "vacation": {...}, "forward": {...} }256```257258- Condition `field`: `from` | `to` | `subject`; `op`: `contains` | `is`. Action `type`: `move` (`folder` created if missing) | `markRead` | `flag` | `trash`. `match`: `all` | `any`. Rules run in order; the first that files a message stops.259- Omitted members are left unchanged (`forward: null` removes forwarding).260- Rules and auto-reply generate **one** Sieve script named `spmail`, byte-for-byte the format of the webmail (`web/src/mail/sieve.ts`), so both stay compatible. `VacationResponse` is deliberately not used (on this mail server it would deactivate the rules script).261- `forward.to` must be on a hosted domain (`400 forward_not_local`); one destination.262- Forwarding and `discard` policies live in a server-managed block of that script (`# spmail-policy:begin … end`). When a client rewrites the script through the JMAP gateway, the server re-inserts the block.263- `raw_sieve` (administrators only) replaces the script with a hand-written one (validated by the mail server: `400 invalid_sieve`); `GET` then reports `managed: false`, and `rules`/`vacation` can no longer be patched (`409 custom_script`). `GET` returns `raw_sieve` to administrators only.264265---266267## 6. Sending268269### 6.1 `POST /messages/send`270271```json272{273  "from": "alerts@spboucher.ai",274  "to": ["simon@spboucher.ai", { "email": "ops@spboucher.ai", "name": "Ops" }],275  "cc": [], "bcc": [],276  "subject": "Disque à 91 %",277  "text": "Le volume /data est à 91 %.",278  "html": "<p>Le volume <b>/data</b> est à 91 %. <img src=\"cid:chart\"></p>",279  "attachments": [ { "file_id": "file_…" }, { "file_id": "file_…", "inline": true, "cid": "chart" } ],280  "reply_to_message_id": "msg_…",281  "headers": { "X-Campaign": "disk-alert", "Reply-To": "ops@spboucher.ai", "List-Unsubscribe": "<mailto:unsub@spboucher.ai>" },282  "priority": "high",283  "send_at": "2026-11-20T13:00:00Z",284  "draft": false285}286```287288| Field | Rules |289|---|---|290| `from` | required; see §4 |291| `to`, `cc`, `bcc` | each ≤ 100 entries, ≤ 100 distinct recipients in total, at least one unless `draft` |292| `subject` | ≤ 998 chars |293| `text`, `html` | at least one (unless `draft`). **`html` is sanitised server-side** with a strict allowlist before it is stored or sent: scripts, event handlers, forms, frames, SVG, `style`/`link`/`meta`, `javascript:`/`data:` URLs (except small PNG/JPEG/GIF/WebP data images), `id`/`class` and dangerous CSS are removed; links get `rel="noopener noreferrer" target="_blank"`. If only `html` is given, a text part is derived from it |294| `attachments` | ≤ 30; `file_id` from `POST /files` (§10.2), uploaded by the same caller for the sender's mailbox; `inline: true` (PNG/JPEG/GIF/WebP only) with a `cid` referenced as `cid:<cid>` in the HTML; needs `mail.attachments.write` |295| `reply_to_message_id` | a message the caller can see: sets `In-Reply-To` and `References` from it |296| `in_reply_to`, `references` | explicit Message-IDs, as an alternative |297| `headers` | **allowlist only**: any `X-…` header (except a few reserved ones such as `X-Spam-Status`), `Reply-To`, `List-Unsubscribe`, `List-Unsubscribe-Post`; ≤ 20. Anything else — `From`, `Sender`, `Return-Path`, `To`, `Bcc`, `Subject`, `DKIM-Signature`, `Received`, `Content-Type`, `Message-ID`… — answers `400 header_not_allowed` |298| `priority` | `high` / `normal` / `low` → `X-Priority` and `Importance` |299| `send_at` | future = scheduled (≤ 30 days ahead, `400 send_at_too_far`); past or now = immediate |300| `draft` | `true` = save only (needs `mail.drafts`) |301| `undo_seconds` | 0–120. **Undo send**: the message is held on the server for that many seconds before it is submitted — `202 scheduled`, with `undo_until` (= `send_at`) in the response. Nothing reaches the mail server's queue before that instant. Cancel with `DELETE /messages/scheduled/{id}` (the stored draft **and its attachments** are destroyed) or, from a device session, with `POST /api/next/compose/undo/{id}` (the message goes back to Drafts intact and its content is returned). Ignored with a future `send_at` (already cancellable), with `draft`, and when the message awaits approval |302| `remind_at`, `remind_if_no_reply` | ISO 8601, ≤ 1 year ahead (`400 remind_at_too_far`). Creates a follow-up reminder on the sent message once it has actually been submitted (never for a cancelled message). **Session callers only**: an API key gets `403 session_required` |303| `confirm_sensitive` | Session callers: required (`true`) when a recipient matches the caller's `sensitive` list (compose preferences, `PUT /api/next/compose/prefs`: addresses or `@domain`). Without it the call answers `409 confirmation_required` with `details.recipients` and nothing is stored or queued. API keys are not concerned |304305**Injection.** CR, LF and other control characters anywhere in an address, display name, subject, header name or header value are refused (`400 invalid_request` / `400 invalid_header`); nothing is sent.306307**Outcomes**308309| HTTP | `status` | Meaning |310|---|---|---|311| 200 | `sent` | handed to the mail server's queue; follow the delivery with `GET /messages/outbound/{id}` or webhooks |312| 200 | `failed` | the mail server refused the submission (`last_error` says why) |313| 202 | `scheduled` | will be submitted at `send_at` (or at `undo_until` for an undo-send hold) |314| 202 | `pending_approval` | external recipients and key policy `approval`: nothing is sent until an administrator approves (`approval_id` returned) |315| 202 | `queued` | the mail server was unreachable; SP Mail will retry (5 s, 15 s, 1 min, 5 min, 15 min, 30 min, 1 h, then `failed`) |316| 201 | `draft` | saved in Drafts; `id` is the draft's `msg_…` id |317318```json319{320  "id": "msg_out_Zk3…", "status": "sent", "from": "alerts@spboucher.ai",321  "message_id": "msg_…", "thread_id": "thr_…",322  "recipients": [ { "address": "simon@spboucher.ai", "status": "sent", "smtp_reply": null } ],323  "external": false, "send_at": null, "attempts": 1, "last_error": null,324  "submitted_at": "2026-11-19T06:04:18.120Z", "final_at": null,325  "created_at": "2026-11-19T06:04:18.001Z", "updated_at": "2026-11-19T06:04:18.120Z"326}327```328329`message_id` is the copy in the sender's mailbox (Drafts until submitted, then Sent).330331### 6.2 External recipients and approval332333A recipient is *external* when its domain is not hosted by this server. For API keys, `external_send_policy` decides:334335| Policy | Behaviour |336|---|---|337| `approval` (**default**) | the message is stored as a server-side draft, a pending approval is created (expires after 7 days), the call answers **202** `{status:"pending_approval", approval_id}`. Nothing is sent — not even to the internal recipients of the same message. An administrator approves (the stored draft is sent and the same `msg_out_…` id goes on to `sent`/`delivered`) or rejects (→ `cancelled`, draft destroyed). Expired approvals are cancelled |338| `allow` | sent directly |339| `deny` | `403 external_send_denied` |340341`allowed_recipient_domains` (optional) further restricts a key: any recipient outside those domains answers `403 recipient_domain_not_allowed`. Sessions are not subject to these policies.342343At submission time (immediately, at `send_at`, or on approval) SP Mail re-checks that the sender address may still send and that the key is still valid; otherwise the message becomes `failed` with an explicit `last_error` and nothing leaves.344345### 6.3 Batch, reply, forward346347- `POST /messages/send-batch` `{ "messages": [ <send body>, … ] }` (≤ 50). Each item is validated, authorised and limited independently; the call answers 200 with `{results:[{index, ok, status, message? , error?}]}`.348- `POST /messages/{id}/reply` `{ text?, html?, reply_all?, from?, cc?, bcc?, attachments?, headers?, send_at?, draft?, undo_seconds?, remind_at?, remind_if_no_reply?, confirm_sensitive? }`. Recipients come from the original (`Reply-To`, else `From`; `reply_all` adds its `To`/`Cc` minus the caller's own addresses), subject gets `Re:`, `In-Reply-To`/`References` keep the thread, the original is flagged answered. `from` defaults to the allowed address the message was delivered to. The original text is not quoted.349- `POST /messages/{id}/forward` `{ to, cc?, bcc?, text?, from?, include_attachments? (default true), send_at?, draft?, undo_seconds?, remind_at?, remind_if_no_reply?, confirm_sensitive? }`. The original's attachments are re-attached and its text quoted under a "Forwarded message" header; the original is flagged forwarded. The sender must be an address of the mailbox that holds the message (`400 cross_mailbox_forward_unsupported`).350351Both use the same policy checks and return the same object as `/messages/send`.352353### 6.4 Tracking and scheduled messages354355| | |356|---|---|357| `GET /messages/outbound?status=&limit=&cursor=` | sends created by the caller, or made from an address the caller can act as; newest first |358| `GET /messages/outbound/{id}` | one send, with per-recipient status and SMTP reply |359| `GET /messages/scheduled` | sends still `scheduled` |360| `DELETE /messages/scheduled/{id}` | cancel → `cancelled`; the stored draft is destroyed; `409 not_cancellable` once it is no longer scheduled |361362---363364## 7. Delivery status vocabulary365366A status only states what was actually observed.367368| Status | What it proves | Final |369|---|---|---|370| `draft` | saved in Drafts, never submitted | — |371| `queued` | accepted by SP Mail, **not yet handed to the mail server** | no |372| `scheduled` | waiting for `send_at` in SP Mail's own persistent queue | no |373| `pending_approval` | waiting for an administrator; nothing was sent | no |374| `sent` | handed to the mail server's outbound queue; **no final answer from the recipient's server yet** | no |375| `deferred` | the recipient's server answered with a temporary failure (4xx); the mail server will retry | no |376| `delivered` | the recipient's mail server accepted the message with a 2xx reply (`smtp_reply`, e.g. `250 2.1.5 OK`). **This is not proof of inbox placement**: the message may still be filtered to spam, quarantined or dropped by the recipient's systems | yes |377| `bounced` | permanent rejection (5xx) by the recipient's server, e.g. `550 5.1.1 Mailbox does not exist.` | yes |378| `failed` | never left: refused by the mail server at submission, sender address or key no longer valid, local rate limit (`452 4.4.5`), or a non-5xx final failure | yes |379| `cancelled` | cancelled before submission (caller, administrator, rejected or expired approval) | yes |380381Each recipient has its own status; the message's `status` is the worst of them, in the order `bounced` > `failed` > `deferred` > `sent` > `queued` > `delivered` (so `delivered` means every recipient was delivered).382383How it is tracked: a background worker polls the mail server's submission record (`EmailSubmission/get → deliveryStatus`) for every non-final send — every 1.5 s during the first minute, every 15 s for 10 minutes, then every 5 minutes, for at most 5 days — and resumes from the database after a restart. For a multi-destination alias the mail server reports one status per member; the alias's own status becomes `delivered` when every member was delivered, otherwise the worst member status.384385---386387## 8. Reading, searching, synchronising388389### 8.1 `GET /messages`390391Newest first (by reception date). Query parameters:392393| Parameter | |394|---|---|395| `address` (or `mailbox`) | comma-separated addresses (§4). Omitted = every address the caller may read |396| `folder` | a role — `inbox`, `drafts`, `sent`, `trash`, `junk`, `archive` — resolved in each mailbox, or a folder id `fld_…`. Omitted = all folders, including Trash, Junk and Drafts |397| `unread`, `flagged`, `has_attachment` | `true` / `false` |398| `from`, `to`, `subject` | substring match (`mail.search`) |399| `text` | full-text search over headers, bodies and, as far as the mail server indexes them, attachments (`mail.search`) |400| `label` | one label (`mail.search`) |401| `after` / `before` | received at or after / strictly before |402| `limit`, `cursor` | §1 |403404**Unified listing.** When several mailboxes are involved, results are merged by date with a composite cursor: one ordered stream, no duplicates, no gaps. This is the "unified inbox" primitive (`?folder=inbox`).405406```json407{ "data": [ {408    "id": "msg_…", "thread_id": "thr_…", "mailbox": "notifications@spboucher.ai", "delivered_to": ["alerts@spboucher.ai"],409    "folders": [ { "id": "fld_…", "role": "inbox", "name": "Inbox" } ],410    "from": [ { "email": "a@example.org", "name": "A" } ], "to": [ … ], "cc": [],411    "subject": "…", "preview": "…", "received_at": "2026-11-19T06:04:18Z", "sent_at": "2026-11-19T06:04:17Z", "size": 3412,412    "unread": true, "starred": false, "draft": false, "answered": false, "forwarded": false, "has_attachment": false, "labels": []413  } ], "next_cursor": "…", "has_more": true }414```415416In a restricted view the address filter is applied by SP Mail after reading from the mail server (`Delivered-To` is not indexed there). At most 3 000 messages per mailbox are examined per request, so a page may be shorter than `limit` while `has_more` is true; keep following `next_cursor`.417418### 8.2 Message, threads419420- `GET /messages/{id}` adds: `bcc`, `reply_to`, `message_id`, `in_reply_to`, `references`, `headers` (`[{name, value}]`), `text`, `html` (**sanitised**, same allowlist as §6.1; remote images are neither fetched nor rewritten), `truncated` (bodies are capped at 1 MB each), `attachments` (`[{id, name, type, size, cid, disposition, inline}]`), `auth` (`{spf, dkim, dmarc, raw}` parsed from `Authentication-Results`, null when absent).421- `GET /threads` — same parameters as `/messages`, one entry per conversation: `{id, mailbox, latest: <message summary>}`.422- `GET /threads/{id}` — `{id, mailbox, messages:[summary…]}`, oldest first, limited to what the caller may see. Threads are per mailbox.423424### 8.3 Incremental sync — `GET /messages/changes`425426Per mailbox (`?address=`, required when the caller can read several).427428```429GET /messages/changes                      → { mailbox, state: "st_…", created: [], updated: [], destroyed: [], has_more: false }430GET /messages/changes?since=st_…&limit=200 → { mailbox, state: "st_… (new)", created: ["msg_…"], updated: ["msg_…"], destroyed: ["msg_…"], has_more }431```432433Bootstrap: list the mailbox, then call without `since` to get the current `state`. Later, call with `since`; repeat while `has_more`. `updated` covers flag, label and folder changes. An unknown, foreign or too old state answers **`409 resync_required`**: list again and take a fresh state. In a restricted view `created`/`updated` are filtered to visible messages; `destroyed` ids are returned unfiltered (ids only).434435### 8.4 Folders436437`GET /folders?address=` → `{data:[{id, mailbox, name, role, parent_id, total, unread}]}` (`total`/`unread` null in restricted views). `POST /folders {address, name, parent_id?}` → 201 (full view and `mail.modify`).438439---440441## 9. Modifying messages442443| | |444|---|---|445| `PATCH /messages/{id}` | `{ "unread": false, "starred": true, "add_labels": ["projet-x"], "remove_labels": ["a_suivre"] }` → message summary. Labels are lower-cased, 1–32 chars of `a-z 0-9 _ . -` starting with a letter or digit (they are JMAP keywords; system keywords such as `$seen` cannot be set this way) |446| `POST /messages/{id}/move` | `{ "folder": "archive" }` — a role (`inbox` = restore, `archive`, `trash`, `junk`, `sent`, `drafts`) or a folder id of the same mailbox. The Archive folder is created with role `archive` when missing |447| `DELETE /messages/{id}` | moves to Trash → `{ok:true, permanent:false}` |448| `DELETE /messages/{id}?permanent=true` | destroys the message. Needs the scope `mail.delete` **and** the body `{"confirm":"permanently-delete"}` (`400 confirmation_required` otherwise) → `{ok:true, permanent:true}` |449450---451452## 10. Drafts and files453454### 10.1 Drafts455456| | |457|---|---|458| `POST /drafts` | same body as `/messages/send` without `send_at`/`draft`; only `from` is required → 201 `{status:"draft", id:"msg_…"}` |459| `GET /drafts?address=&limit=&cursor=` | drafts of the readable mailboxes |460| `GET /drafts/{id}` | full message |461| `PATCH /drafts/{id}` | given fields replace the draft's; attachments are kept unless `attachments` is given. **The response carries a new `id`** (messages are immutable on the mail server: the draft is recreated, the old id is gone) |462| `DELETE /drafts/{id}` | destroys the draft (`409 draft_in_use` if it backs a scheduled or pending send) |463| `POST /drafts/{id}/send` | `{ "send_at"? }` — same checks and outcomes as `/messages/send`; `409 draft_in_use` if already being sent |464465Draft HTML is sanitised when stored: what the webmail later displays is never the caller's raw HTML.466467### 10.2 Files468469```bash470curl -X POST "$BASE/files?filename=rapport.pdf&address=contact@spboucher.ai" \471  -H "Authorization: Bearer $KEY" -H 'Content-Type: application/pdf' --data-binary @rapport.pdf472# 201 → { "id": "file_…", "name": "rapport.pdf", "type": "application/pdf", "size": 30000, "mailbox": "contact@spboucher.ai", "expires_at": "…" }473```474475Raw bytes as the request body, with the file's `Content-Type` (any type is stored as bytes, never interpreted; `multipart/form-data` → `415 multipart_not_supported`). Max 50 MB. `address` selects the mailbox (required when the caller can send from several). A file can only be attached by the caller that uploaded it, to a message sent from that mailbox (`400 unknown_file`, `400 file_wrong_mailbox`). Files expire after 24 h at most; see §14 for the mail server's own retention of unattached uploads.476477### 10.3 Attachments of received mail478479`GET /messages/{id}/attachments` → `{data:[attachment]}`; `GET /messages/{id}/attachments/{attachment_id}` → the bytes, always with `Content-Disposition: attachment`, `Content-Type: application/octet-stream`, `Content-Security-Policy: sandbox; default-src 'none'` and `X-Content-Type-Options: nosniff` (images included). The attachment id is verified against that message.480481---482483## 11. Webhooks and events484485### 11.1 Managing486487| | |488|---|---|489| `POST /webhooks` | `{ name, url, events:[…], address_ids?:[uuid], include_content? (false), active? (true) }` → 201, with `secret` (`whsec_…`) **shown once** |490| `GET /webhooks`, `GET /webhooks/{id}` | a key sees only its own webhooks; an administrator session sees all |491| `PATCH /webhooks/{id}` | any creation field, plus `rotate_secret: true` (returns the new secret once; sessions need re-authentication) |492| `DELETE /webhooks/{id}` | also removes its delivery history |493| `GET /webhooks/{id}/deliveries?status=&limit=&cursor=` | attempts, newest first: `{id, event_id, event_type, status: pending|retrying|delivered|failed, attempt, next_attempt_at, last_status, last_error, delivered_at, created_at}` |494| `POST /webhooks/{id}/test` | sends a signed `webhook.test` event now → `{delivery, http_status, error}` |495| `POST /webhook-deliveries/{id}/replay` | queues the delivery again (same event id, new timestamp and signature, attempt counter reset) |496| `GET /events?type=&limit=&cursor=` | recent events visible to the caller, newest first, metadata only (never `subject`/`preview`), kept 30 days |497498**Who receives what.** A key-owned webhook only receives events for addresses the key can see (address in its allowlist, or mailbox primary address in its allowlist); a revoked or expired key receives nothing. `address_ids` narrows further (for a key: only addresses of its allowlist, `403 address_not_allowed`). An administrator-owned webhook (created with a session) receives every event matching its filters.499500**Destination rules (SSRF guard).** The URL must be `https` on port 443, without credentials, and **every** address its host resolves to must be public: loopback, private (RFC 1918), link-local, CGNAT, unique-local, multicast, IPv4-mapped/NAT64/6to4 forms of those, and unresolvable hosts are refused (`403 forbidden_destination`; malformed or non-http(s) URLs `400 invalid_url`). The only exception is a `host:port` that an administrator explicitly added to the internal allowlist (`/api/admin/webhook-allowlist`, exact match, `http` allowed there). The check is repeated at **every delivery**, and the connection is pinned to the address that was checked (no second DNS resolution). **Redirects are never followed**: a 3xx answer is a failed attempt (`redirect_not_followed`).501502### 11.2 Events503504| Type | Emitted when | `data` |505|---|---|---|506| `message.received` | a message arrives in a mailbox (any folder except Drafts/Sent; a message filed to Junk or by a rule is included, see `folders`) | `message_id, thread_id, address, from[], to[], cc[], delivered_to[], received_at, size, has_attachment, folders[]` (+ `subject, preview` with `include_content`) |507| `message.sent` | a send created through the API was handed to the mail server | `outbound_id, message_id, from, status, recipients[{address,status,smtp_reply}]` |508| `message.delivered` / `message.deferred` / `message.bounced` / `message.failed` | the overall status of an API send changed to that value (§7) | same as `message.sent` |509| `message.read` | a tracked received message got the read flag | `message_id, thread_id, address` |510| `message.deleted` | a tracked received message was moved to Trash (`permanent:false`) or destroyed (`permanent:true`) | `message_id, address, permanent` |511| `draft.created` | a draft was created through the API | `message_id, from, to[]` |512| `address.created` | an address was created through the API | `address_id, address, kind` |513| `address.suspended` | an address was suspended (`reason: "suspended"`) or expired (`reason: "expired"`) | `address_id, address, reason` |514| `rule.matched` | a post-delivery rule (SP Mail Next, `/api/next/rules`) matched a received message and ran an `event` or `notify_app` action | `rule_id, rule_name, name, app?, message_id, thread_id, address, from[], received_at` (+ `subject, preview` with `include_content`) |515516`address` is the address the event belongs to: for `message.received`, the envelope recipient (`Delivered-To`) when it is an address of the mailbox, else the mailbox's primary address; for sends, the `from` address.517518**Content.** With `include_content: false` (default) a payload carries ids, addresses, dates, sizes and statuses only — no subject, no preview, no body. With `include_content: true` (key needs `mail.read`) `message.received` additionally carries `subject` and `preview` (≤ 256 chars). Bodies and attachments are never sent; fetch them with `GET /messages/{id}`.519520**How reception is detected.** A watcher follows each mailbox's change feed from a state persisted in the database (default every 5 s). Nothing is lost across restarts; the event, the tracking row and the new state are written in one transaction. If the mail server no longer knows the stored state, the watcher restarts from the current state **without re-emitting** old messages. `message.read` and `message.deleted` are best effort: they are detected for messages whose `message.received` was emitted by the watcher, for 30 days.521522### 11.3 Delivery523524`POST <url>` with the JSON payload:525526```json527{ "id": "evt_Qm1…", "type": "message.received", "occurred_at": "2026-11-19T06:04:19.412Z",528  "address": "alerts@spboucher.ai", "mailbox": "notifications@spboucher.ai",529  "data": { "message_id": "msg_…", "thread_id": "thr_…", "address": "alerts@spboucher.ai", "from": ["a@example.org"], "to": ["alerts@spboucher.ai"], "cc": [],530            "delivered_to": ["alerts@spboucher.ai"], "received_at": "2026-11-19T06:04:18Z", "size": 3412, "has_attachment": false, "folders": ["inbox"] } }531```532533Headers: `SPMail-Signature`, `SPMail-Event-Id`, `SPMail-Event-Type`, `SPMail-Delivery-Attempt` (1, 2, …), `User-Agent: SPMail-Webhooks/1`, `Content-Type: application/json`.534535- **Success** = any 2xx within 10 s. The response body is ignored (at most 64 kB are read).536- **Retries**: after a failure the delivery is retried after 1 min, 5 min, 30 min, 2 h, 6 h and 24 h (7 attempts in all), then marked `failed`. The queue is persistent: pending deliveries survive a restart.537- **At-least-once**: a receiver may see the same event twice (a retry after a lost answer, or a manual replay). Deduplicate on `SPMail-Event-Id`. Ordering is not guaranteed.538539### 11.4 Verifying the signature540541```542SPMail-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, t + "." + raw request body)>543```544545Compute the HMAC over the **raw body bytes** (before any JSON parsing), compare in constant time, and reject timestamps more than 5 minutes away from your clock (replay window).546547```js548// Node549import crypto from "node:crypto"550function verify(secret, header, rawBody, toleranceSec = 300) {551  const m = /^t=(\d+),v1=([0-9a-f]{64})$/.exec(header ?? "")552  if (!m) return false553  if (Math.abs(Date.now() / 1000 - Number(m[1])) > toleranceSec) return false554  const expected = crypto.createHmac("sha256", secret).update(`${m[1]}.${rawBody}`).digest()555  const given = Buffer.from(m[2], "hex")556  return given.length === expected.length && crypto.timingSafeEqual(given, expected)557}558// express: app.post("/hook", express.raw({ type: "application/json" }), (req, res) => {559//   if (!verify(SECRET, req.get("SPMail-Signature"), req.body.toString("utf8"))) return res.sendStatus(400)560//   const event = JSON.parse(req.body); /* dedupe on event.id */ res.sendStatus(204) })561```562563```python564# Python565import hashlib, hmac, re, time566def verify(secret: str, header: str, raw_body: bytes, tolerance: int = 300) -> bool:567    m = re.fullmatch(r"t=(\d+),v1=([0-9a-f]{64})", header or "")568    if not m or abs(time.time() - int(m.group(1))) > tolerance:569        return False570    expected = hmac.new(secret.encode(), m.group(1).encode() + b"." + raw_body, hashlib.sha256).hexdigest()571    return hmac.compare_digest(expected, m.group(2))572```573574---575576## 12. Introspection577578- `GET /health` (public) → `{ok, version, database: "ok"|"down", mail_server: "reachable"|"unreachable", workers: "on"|"off"}`; 503 when not ok.579- `GET /me` →580581```json582{ "type": "key", "id": "…", "name": "agent-alertes", "explorer": false, "scopes": ["mail.read", "mail.send"], "all_addresses": false,583  "addresses": [ { "id": "…", "address": "alerts@spboucher.ai", "kind": "alias", "mailbox": "notifications@spboucher.ai", "status": "active", "can_send": true, "can_receive": true, "read": "restricted" } ],584  "limits": { "rate_per_minute": 60, "daily_send_limit": 200, "external_send_policy": "approval", "allowed_recipient_domains": [] },585  "usage_today": { "sent": 3, "requests": 41 }, "version": "…" }586```587588`read` is `full`, `restricted` or `none` (see §4). For a session: `type: "user"`, `limits` null/`allow`.589- `GET /openapi.json`, `GET /openapi.yaml` (public) — OpenAPI 3.1; each operation lists its scopes in `x-required-scopes`.590591---592593## 13. Administration (session only)594595Under `/api/admin/…`: a session with role `admin`. These routes keep the legacy error envelope `{"error":"code","message":"…"}` and the web CSRF rules. ⟳ = needs a recent re-authentication (§2). All previously existing `/api/admin/*` routes are unchanged.596597**API keys**598599| | |600|---|---|601| `GET /api/admin/api-keys`, `GET …/{id}` | `{id, name, description, prefix, scopes, address_ids, all_addresses, rate_per_minute, daily_send_limit, external_send_policy, allowed_recipient_domains, expires_at, revoked_at, last_used_at, created_by, rotated_from, created_at, state: active|revoked|expired}` |602| `POST /api/admin/api-keys` ⟳ | `{name, scopes, description?, address_ids?, all_addresses?, rate_per_minute? (60), daily_send_limit? (200), external_send_policy? ("approval"), allowed_recipient_domains?, expires_at?}` → 201 `{key, token}` — **the only time the token is shown** |603| `PATCH …/{id}` ⟳ | same fields; effective at the key's next request |604| `POST …/{id}/rotate` ⟳ | `{grace_seconds? (0, max 7 days)}` → 201 `{key (new id, same settings, rotated_from), token, previous}`. The previous key is revoked immediately, or at the end of the grace period. Its webhooks move to the new key |605| `DELETE …/{id}` | immediate revocation (also kills its explorer tokens) |606| `GET …/{id}/usage?days=7` | `{key, by_day:[{day, requests, errors, explorer}], by_route:[{method, route, requests, errors, avg_ms}], sends:{status:n}, recent:[{at, method, route, status, duration_ms, ip, error_code, explorer}]}` |607| `POST …/{id}/explorer-token` | 201 `{token: "spx_…", expires_at, key_id, purpose: "explorer"}` |608609The usage log records, per key request: time, method, **route template** (e.g. `/api/v1/messages/{id}`), status, duration, IP, error code, explorer flag. Never bodies, tokens, ids or query strings. Kept 90 days.610611**Approvals** — `GET /api/admin/approvals?status=pending|approved|rejected|expired` → `[{id, status, outbound_id, outbound_status, key_id, key_name, from, recipients, external_recipients, subject, preview, send_at, created_at, expires_at, decided_at}]` (subject and preview are read live from the stored draft for pending approvals, never copied to the database) · `POST …/{id}/approve` ⟳ → `{ok, approval_id, outbound}` · `POST …/{id}/reject` → `{ok, approval_id, outbound}` · `409 not_pending` when already decided or expired.612613**Webhook internal allowlist** — `GET /api/admin/webhook-allowlist` · `POST` ⟳ `{host_port: "127.0.0.1:9000", note?}` · `DELETE ?host_port=` ⟳.614615**Scheduled messages** — `GET /api/admin/scheduled` · `DELETE /api/admin/scheduled/{id}`.616617**Metrics** — `GET /api/admin/metrics?days=14` → `{by_day:[{day, <status>: n}], by_address:[{address, <status>: n}], queue_depth:{<status>:{count, oldest}}, webhook_backlog:{pending|retrying|failed:{count, oldest}}, pending_approvals}`.618619**Shared mailboxes** — `GET /api/admin/mailboxes/{id}/grants` · `PUT` ⟳ `{grants:[{user_id, can_read, can_send}]}` (replaces the list; the mailbox's primary address becomes kind `shared` while grants exist).620621**Addresses** — `POST /api/admin/addresses/sync` (same as `cli addresses-sync`: idempotent, read-only on the mail server) · `POST /api/admin/retention/run` ⟳ (runs retention now).622623**Retention.** Opt-in per mailbox, default off: `retention_trash_days`, `retention_junk_days` (messages older than N days in Trash / Junk) and `retention_days` (any folder) on the primary address. A worker runs once per 24 h, permanently deletes matching messages, and writes one `retention.run` audit entry per mailbox with the counts.624625---626627## 14. Limits and what is not supported628629**Limits**630631| | |632|---|---|633| JSON body | 1 MB; 6 MB on composing routes |634| File upload | 50 MB per file; ≤ 30 attachments per message |635| Recipients | ≤ 100 per message; batch ≤ 50 messages |636| Scheduling | ≤ 30 days ahead |637| Page size | ≤ 100 |638| Custom headers | ≤ 20, values ≤ 900 chars |639| Message bodies returned | 1 MB per part (`truncated: true` beyond) |640| Mail-server rate limit | about 25 messages per hour for one sender-domain → recipient pair; beyond it the submission is accepted and the recipient ends `failed` with `452 4.4.5 Rate limit exceeded` |641642**Not supported / honest caveats**643644- **`delivered` is not inbox placement** (§7). Bounces that a remote system sends *later* as a DSN e-mail (after having accepted the message with 250) are not correlated with the send: they arrive as ordinary mail in the sender's mailbox.645- `message.sent/delivered/deferred/bounced/failed` exist only for sends made through `/api/v1`. Mail sent from the webmail or the native apps is not tracked (those clients read `deliveryStatus` themselves).646- `message.read` / `message.deleted` are best effort (§11.2). Messages destroyed that the watcher never tracked produce no event.647- Reception is detected by polling (default 5 s), not by a push stream.648- `multipart/form-data` uploads are not parsed; `POST /files` is not idempotent.649- Sorting is newest-first only.650- Threads are per mailbox; in address-restricted views threads are collapsed per page (a conversation may reappear on a later page).651- `PATCH /drafts/{id}` returns a new id.652- Forwarding across mailboxes is refused. Automation forwarding has one destination, on a hosted domain only (the mail server allows a single Sieve redirect). `extra_destinations` accepts local addresses only.653- Quota and retention apply to physical mailboxes, not to individual aliases.654- `can_send: false` / `receive_only` are enforced by `/api/v1`. The JMAP gateway used by the webmail is blocked at the mail server only for a *suspended mailbox*.655- An address that the mail server does not hold as an enabled alias (reception rejected, or multi-destination list) is sent with the mailbox's identity: header `From` = the address, SMTP envelope sender = the mailbox's primary address.656- Signatures are stored on the address and synchronised to the sending identity, but are not appended automatically to API messages. Replies do not quote the original.657- The per-key rate limit is kept in memory (single instance; it restarts with the process). Daily limits, queues, schedules and webhook deliveries are persistent.658- Sends are at-least-once at the boundary with the mail server: if the process dies after the mail server accepted a submission but before SP Mail recorded it, the dispatcher submits the message again after its lease (2 min) expires.659- The mail server keeps *unattached* uploads for a limited time of its own; a file whose blob has gone answers `400 file_expired` when attached. Upload shortly before sending.660- No sending to distribution lists by name, no templates, no open/click tracking (by design).661662---663664## 15. Error codes665666| HTTP | Codes |667|---|---|668| 400 | `invalid_request` (validation; `details.issues`), `token_in_url`, `invalid_cursor`, `invalid_idempotency_key`, `invalid_header`, `header_not_allowed`, `no_recipients`, `too_many_recipients`, `empty_message`, `send_at_too_far`, `remind_at_too_far`, `unknown_file`, `file_wrong_mailbox`, `file_expired`, `invalid_inline_image`, `invalid_content_type`, `message_rejected`, `confirmation_required`, `unknown_folder`, `address_required`, `cross_mailbox_forward_unsupported`, `unknown_domain`, `mailbox_required`, `unknown_mailbox`, `unknown_user`, `unknown_address`, `invalid_destination`, `extra_destinations_alias_only`, `extra_destinations_need_receive`, `expires_at_required`, `kind_change_unsupported`, `quota_mailbox_only`, `retention_mailbox_only`, `forward_not_local`, `forward_loop`, `invalid_sieve`, `invalid_url` |669| 401 | `unauthenticated`, `invalid_api_key`, `key_revoked`, `key_expired` |670| 403 | `insufficient_scope`, `session_required`, `from_not_allowed`, `address_inactive`, `address_cannot_send`, `address_not_allowed`, `mailbox_scope_required`, `admin_required`, `protected_address`, `external_send_denied`, `recipient_domain_not_allowed`, `forbidden_destination`, `reauth_required`, `csrf` |671| 404 | `not_found` (unknown **or** not visible to the caller — deliberately indistinguishable) |672| 409 | `confirmation_required` (sensitive recipient, `details.recipients`), `idempotency_conflict`, `idempotency_in_progress`, `idempotency_key_expired`, `resync_required`, `address_taken`, `not_cancellable`, `not_a_draft`, `draft_in_use`, `not_a_mailbox`, `custom_script`, `folder_not_created` |673| 413 | `payload_too_large`, `file_too_large` |674| 415 | `multipart_not_supported`, `unsupported_media_type` |675| 429 | `rate_limited`, `daily_send_limit_exceeded` |676| 500 | `internal` |677| 502 | `mail_server_unavailable`, `mail_server_error` |678| 503 | (`GET /health` only) |679680## 15b. Templates (send by template)681682Templates are authored in the webmail studio (manually or generated with AI) and belong to a user. A session sees its own library; an API key sees the library of the user who created the key. Session-side authoring routes are documented in `docs/templates-api.md`.683684| Endpoint | Scope | Purpose |685|---|---|---|686| `GET /templates` | `mail.send` or `mail.drafts` | List templates (no HTML) |687| `GET /templates/{id}` | same | Template with `html` and `text` |688| `POST /templates/{id}/render` | same | `{variables, use_examples?}` → `{subject, preheader, html, text, missing}`; nothing is sent |689| `POST /messages/send` with `template_id` | `mail.send` | Send the rendered template |690691```json692POST /api/v1/messages/send693{694  "from": "notifications@spboucher.ai",695  "to": [{ "email": "recette@stg.spboucher.ai" }],696  "template_id": "6f1c0c1e-…",697  "variables": { "first_name": "Zoé", "code": "424242", "action_url": "https://wallet.spboucher.ai/verify" }698}699```700701Rules: with `template_id`, `html` and `text` must be omitted (`400 template_conflict`); `subject` is optional and overrides the template's; every variable marked required must be supplied (`400 missing_variables`, no example value is ever substituted in a real send); unknown variable names are refused (`400 unknown_variables`); an unknown or foreign template is `404 unknown_template`. Values are HTML-escaped; a value used inside an `href`/`src` attribute must be an `http(s)` or `mailto` URL, otherwise the attribute becomes `#`. The template's layout (`<style>`, media queries, Outlook conditional comments) is preserved: stored templates were sanitised when saved by the template sanitiser, which removes active content but keeps email layout — unlike caller-supplied `html`, which always goes through the strict allowlist. All other send rules (address allowlist, external-send policy, limits, idempotency, scheduling, statuses) apply unchanged.702703704## 16. Clarifications (2026-11-19, found while building the SDKs)705706- **Alias management by key** — a key with `mail.aliases.manage` may create an alias on a mailbox in its allowlist, but can only read, update or delete aliases that are themselves in its address allowlist. A newly created alias is not added to the creating key's allowlist: an administrator must add it (otherwise `404`).707- **Search** — `subject`, `from`, `to` and `text` filters match whole words (the mail server's full-text index), not arbitrary substrings.708- **Forward** — `POST /messages/{id}/forward` requires `mail.read` in addition to `mail.send` (a send-only key cannot forward a message it cannot read). The OpenAPI `x-scopes` list is "any of" and cannot express this.709- **Drafts** — `POST /drafts` returns the full outbound-shaped object with `status: "draft"`, as in the OpenAPI document.710- **Validation errors are `400`**; the API never answers `422`.711- **Templates are supported** (see §15); the "no templates" line in §14 is obsolete. Template errors: `400 template_conflict`, `400 missing_variables`, `400 unknown_variables`, `404 unknown_template`. `GET /templates` answers `{ "templates": […] }`.712- **OpenAPI gaps** — `send-batch` items are untyped in the document (each item has the `POST /messages/send` body); the `201`/`202` answers of send, reply, forward and draft-send carry the same body as the `200` answer.713
Files main
Menu

Theme