SPB Git

Repository Public

API.md 60.4 KB

# SP Mail — REST API v1

Base URL: https://mail.spboucher.ai/api/v1 (dev: http://localhost:8731/api/v1). Machine-readable contract: 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.

This document describes what is implemented and tested (tests/integration/v1-*.test.ts). Everything that is not supported is listed in §14. The session / JMAP-gateway contract of the web and native apps is unchanged and stays in api-contract.md.

Contents: 1 Conventions · 2 Authentication · 3 Scopes · 4 Address-level authorization · 5 Addresses and aliases · 6 Sending · 7 Delivery status · 8 Reading · 9 Modifying · 10 Drafts and files · 11 Webhooks and events · 12 Introspection · 13 Administration · 14 Limits · 15 Errors


# 1. Conventions

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).

Errors always use one envelope, with the HTTP status carrying the class:

json
{ "error": { "code": "from_not_allowed", "message": "This caller is not allowed to send from that address", "details": { } } }

details is optional (validation issues, limits, offending recipients…). Codes are listed in §15. Unknown paths under /api/v1/ answer JSON 404 not_found (never the webmail page).

Request ids. Every response carries X-Request-Id: req_…; quote it when reporting a problem.

Pagination. List endpoints take ?limit= (1–100, default 25) and ?cursor= and answer

json
{ "data": [ … ], "next_cursor": "eyJ2IjoxLC…", "has_more": true }

Cursors 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).

Idempotency. POST routes that create or send accept Idempotency-Key: <1–200 printable ASCII chars>:

Situation Result
first request processed; status and body are stored for 24 h
same key, same request (method, route, path/query parameters, body) the stored status and body, plus Idempotency-Replayed: true
same key, different request 409 idempotency_conflict
same key while the first is still running 409 idempotency_in_progress

Deterministic 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).

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.

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.

Dates are ISO 8601 UTC.


# 2. Authentication

# API keys

text
Authorization: Bearer spm_<prefix>_<secret>
  • 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.
  • 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.
  • 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.
  • 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.
  • 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>.

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.

# Sessions (the owner's own tools)

Every /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), mail.admin if the user's role is admin. Sessions are not subject to the per-key limits nor to the external-send policy.

# Re-authentication (sessions only)

Sensitive session operations need a passkey assertion made within the last 5 minutes, bound to the current session and user; otherwise 403 reauth_required.

text
POST /api/reauth/options   {}                         → { challenge_id, options }      (WebAuthn request options, allowCredentials = the user's passkeys)
POST /api/reauth/verify    { challenge_id, response }  → { ok, reauth_at, valid_until }

Operations 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}.


# 3. Scopes

mail.admin implies every other scope. Session callers hold every scope except mail.admin (administrators hold it too).

Scope Allows
mail.send send, reply, send a draft, batch; read the status of sends; scheduled messages
mail.read list and read messages, threads, folders, incremental sync; read events
mail.search use search filters (from, to, subject, text, label)
mail.modify read/unread, star, labels, move, archive, trash, create folders
mail.delete permanent deletion (also allows trash)
mail.drafts create, list, read, update, discard drafts
mail.attachments.read list and download attachments
mail.attachments.write upload files and attach them
mail.addresses.read list addresses and read mailbox automation
mail.addresses.manage create / update / delete alias-type addresses, write automation
mail.aliases.manage create / update / delete alias-type addresses
mail.webhooks.manage manage the key's own webhooks, deliveries, replay
mail.admin everything, plus: create / suspend / delete physical mailboxes, protected, raw Sieve, all_addresses
Endpoint Scope (any of)
GET /health, GET /openapi.json, GET /openapi.yaml none (public)
GET /me any authenticated caller
GET /messages, GET /threads mail.read (no search filter) · mail.search (with from/to/subject/text/label; /threads then needs both)
GET /messages/{id}, GET /threads/{id}, GET /messages/changes, GET /folders mail.read
PATCH /messages/{id}, POST /messages/{id}/move, POST /folders mail.modify
DELETE /messages/{id} mail.modify or mail.delete; ?permanent=true needs mail.delete
GET /messages/{id}/attachments[/{attachment_id}] mail.attachments.read
POST /files mail.attachments.write
POST /messages/send mail.send (draft: true → mail.drafts); with attachments also mail.attachments.write
POST /messages/send-batch, POST /messages/{id}/reply, POST /drafts/{id}/send mail.send
POST /messages/{id}/forward mail.send and mail.read
GET /messages/outbound[/{id}] mail.send or mail.read
GET /messages/scheduled, DELETE /messages/scheduled/{id} mail.send
POST/GET /drafts, GET/PATCH/DELETE /drafts/{id} mail.drafts
GET /addresses, GET /addresses/{id}, GET /aliases, GET /addresses/{id}/automation mail.addresses.read
POST /addresses, PATCH/DELETE /addresses/{id}, POST /aliases, PATCH/DELETE /aliases/{id} mail.addresses.manage or mail.aliases.manage (mailbox kinds: mail.admin)
PUT /addresses/{id}/automation mail.addresses.manage (raw_sieve: mail.admin)
/webhooks…, POST /webhook-deliveries/{id}/replay mail.webhooks.manage
GET /events mail.read, mail.webhooks.manage or mail.send

A missing scope answers 403 insufficient_scope with details.required.


# 4. Address-level authorization

A 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.

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.

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).

Reading. For each mailbox reachable through the allowlist the key gets one view:

The allowlist contains View
the mailbox's primary address (active) full: every message of the mailbox
only alias-type addresses of that mailbox restricted to those addresses

In a restricted view a message is visible if and only if at least one of these is an allowed address:

  • an envelope recipient recorded by the mail server at delivery (header Delivered-To, added by the server, not by the sender);
  • an address in To, Cc or Bcc;
  • the address in From (mail sent as that address).

Everything 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).

Passing ?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.

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).

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.

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.


# 5. Addresses and aliases

# 5.1 The address object

json
{
  "id": "0d6f…", "address": "alerts@spboucher.ai", "kind": "alias",
  "mailbox": "notifications@spboucher.ai", "mailbox_id": "9a1c…",
  "display_name": "Alertes", "signature_text": "", "signature_html": "", "avatar": null,
  "can_send": true, "can_receive": true,
  "status": "active", "suspended_reason": null, "expired": false, "expires_at": null,
  "retention_days": null, "retention_trash_days": null, "retention_junk_days": null, "quota_bytes": null,
  "reply_policy": "reject", "protected": false, "extra_destinations": [],
  "inbound": "accept",
  "created_at": "2026-11-19T06:00:00.000Z", "updated_at": "2026-11-19T06:00:00.000Z"
}
Field Meaning
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
can_send / can_receive forced by send_only (true/false) and receive_only (false/true)
status active or suspended; suspended_reason is "expired" when the expiry worker suspended it
expires_at required for temporary; allowed on any alias-type address
reply_policy what happens to incoming mail when the address does not receive (can_receive false or kind send_only): reject (default), accept, discard
inbound read-only: what the mail server does now with mail for this address — accept, reject (SMTP 550) or discard (accepted, then dropped)
protected never deletable nor destructively modifiable, by any API
extra_destinations other local addresses that also receive mail sent to this alias
avatar `data:image/(png
retention_*, quota_bytes physical mailboxes only (set on the primary address)

# 5.2 Enforcement is real

A 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:

State Effect on the mail server Effect in the API
alias-type, inbound: accept account alias enabled —
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
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; }) —
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
physical mailbox, can_receive: false + reject emailReceive disabled —
receive_only or can_send: false — sending refused (403 address_cannot_send) — enforced by /api/v1 only
quota_bytes account quota maxDiskQuota —
extra_destinations non-empty the address becomes a mail-server mailing list whose recipients are the mailbox and the extra destinations —
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") —

Sending 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.

# 5.3 Endpoints

GET /addresses?kind=&mailbox=&status= addresses visible to the caller (key: its allowlist; administrator session: all) → {data:[address]}
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
GET /addresses/{id} {id} is the UUID or the address itself
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
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}
GET /aliases, POST /aliases, PATCH /aliases/{id}, DELETE /aliases/{id} the same, restricted to alias-type addresses (a mailbox id answers 404)
GET /addresses/{id}/automation, PUT … filters, auto-reply, forwarding of a mailbox (§5.5)
bash
curl -X POST $BASE/aliases -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{
  "address": "sales@spboucher.ai", "mailbox": "contact@spboucher.ai", "display_name": "Ventes" }'
# 201 → the address object (kind "alias", inbound "accept")

curl -X PATCH $BASE/aliases/sales@spboucher.ai -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"status":"suspended"}'
# 200 → status "suspended", inbound "reject"   (mail to it now bounces with 550 5.1.1)

Rules: 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).

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.

# 5.4 Multi-destination aliases

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).

# 5.5 Automation (filters, auto-reply, forwarding)

Per physical mailbox; {id} must be its primary address (409 not_a_mailbox otherwise) and the caller needs a full view of it.

json
PUT /addresses/contact@spboucher.ai/automation
{
  "rules": [ { "id": "r1", "name": "Factures", "enabled": true, "match": "all",
               "conditions": [ { "field": "subject", "op": "contains", "value": "facture" } ],
               "actions": [ { "type": "move", "folder": "Factures" }, { "type": "flag" } ] } ],
  "vacation": { "enabled": true, "subject": "Absent", "text": "De retour lundi.", "from": "2026-12-20", "to": "2027-01-04", "days": 3 },
  "forward": { "to": "simon@spboucher.ai", "keep_copy": true }
}
→ { "managed": true, "active": true, "rules": [...], "vacation": {...}, "forward": {...} }
  • 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.
  • Omitted members are left unchanged (forward: null removes forwarding).
  • 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).
  • forward.to must be on a hosted domain (400 forward_not_local); one destination.
  • 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.
  • 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.

# 6. Sending

# 6.1 POST /messages/send

json
{
  "from": "alerts@spboucher.ai",
  "to": ["simon@spboucher.ai", { "email": "ops@spboucher.ai", "name": "Ops" }],
  "cc": [], "bcc": [],
  "subject": "Disque à 91 %",
  "text": "Le volume /data est à 91 %.",
  "html": "<p>Le volume <b>/data</b> est à 91 %. <img src=\"cid:chart\"></p>",
  "attachments": [ { "file_id": "file_…" }, { "file_id": "file_…", "inline": true, "cid": "chart" } ],
  "reply_to_message_id": "msg_…",
  "headers": { "X-Campaign": "disk-alert", "Reply-To": "ops@spboucher.ai", "List-Unsubscribe": "<mailto:unsub@spboucher.ai>" },
  "priority": "high",
  "send_at": "2026-11-20T13:00:00Z",
  "draft": false
}
Field Rules
from required; see §4
to, cc, bcc each ≤ 100 entries, ≤ 100 distinct recipients in total, at least one unless draft
subject ≤ 998 chars
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
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
reply_to_message_id a message the caller can see: sets In-Reply-To and References from it
in_reply_to, references explicit Message-IDs, as an alternative
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
priority high / normal / low → X-Priority and Importance
send_at future = scheduled (≤ 30 days ahead, 400 send_at_too_far); past or now = immediate
draft true = save only (needs mail.drafts)
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
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
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

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.

Outcomes

HTTP status Meaning
200 sent handed to the mail server's queue; follow the delivery with GET /messages/outbound/{id} or webhooks
200 failed the mail server refused the submission (last_error says why)
202 scheduled will be submitted at send_at (or at undo_until for an undo-send hold)
202 pending_approval external recipients and key policy approval: nothing is sent until an administrator approves (approval_id returned)
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)
201 draft saved in Drafts; id is the draft's msg_… id
json
{
  "id": "msg_out_Zk3…", "status": "sent", "from": "alerts@spboucher.ai",
  "message_id": "msg_…", "thread_id": "thr_…",
  "recipients": [ { "address": "simon@spboucher.ai", "status": "sent", "smtp_reply": null } ],
  "external": false, "send_at": null, "attempts": 1, "last_error": null,
  "submitted_at": "2026-11-19T06:04:18.120Z", "final_at": null,
  "created_at": "2026-11-19T06:04:18.001Z", "updated_at": "2026-11-19T06:04:18.120Z"
}

message_id is the copy in the sender's mailbox (Drafts until submitted, then Sent).

# 6.2 External recipients and approval

A recipient is external when its domain is not hosted by this server. For API keys, external_send_policy decides:

Policy Behaviour
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
allow sent directly
deny 403 external_send_denied

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.

At 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.

# 6.3 Batch, reply, forward

  • 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?}]}.
  • 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.
  • 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).

Both use the same policy checks and return the same object as /messages/send.

# 6.4 Tracking and scheduled messages

GET /messages/outbound?status=&limit=&cursor= sends created by the caller, or made from an address the caller can act as; newest first
GET /messages/outbound/{id} one send, with per-recipient status and SMTP reply
GET /messages/scheduled sends still scheduled
DELETE /messages/scheduled/{id} cancel → cancelled; the stored draft is destroyed; 409 not_cancellable once it is no longer scheduled

# 7. Delivery status vocabulary

A status only states what was actually observed.

Status What it proves Final
draft saved in Drafts, never submitted —
queued accepted by SP Mail, not yet handed to the mail server no
scheduled waiting for send_at in SP Mail's own persistent queue no
pending_approval waiting for an administrator; nothing was sent no
sent handed to the mail server's outbound queue; no final answer from the recipient's server yet no
deferred the recipient's server answered with a temporary failure (4xx); the mail server will retry no
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
bounced permanent rejection (5xx) by the recipient's server, e.g. 550 5.1.1 Mailbox does not exist. yes
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
cancelled cancelled before submission (caller, administrator, rejected or expired approval) yes

Each 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).

How 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.


# 8. Reading, searching, synchronising

# 8.1 GET /messages

Newest first (by reception date). Query parameters:

Parameter
address (or mailbox) comma-separated addresses (§4). Omitted = every address the caller may read
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
unread, flagged, has_attachment true / false
from, to, subject substring match (mail.search)
text full-text search over headers, bodies and, as far as the mail server indexes them, attachments (mail.search)
label one label (mail.search)
after / before received at or after / strictly before
limit, cursor §1

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).

json
{ "data": [ {
    "id": "msg_…", "thread_id": "thr_…", "mailbox": "notifications@spboucher.ai", "delivered_to": ["alerts@spboucher.ai"],
    "folders": [ { "id": "fld_…", "role": "inbox", "name": "Inbox" } ],
    "from": [ { "email": "a@example.org", "name": "A" } ], "to": [ … ], "cc": [],
    "subject": "…", "preview": "…", "received_at": "2026-11-19T06:04:18Z", "sent_at": "2026-11-19T06:04:17Z", "size": 3412,
    "unread": true, "starred": false, "draft": false, "answered": false, "forwarded": false, "has_attachment": false, "labels": []
  } ], "next_cursor": "…", "has_more": true }

In 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.

# 8.2 Message, threads

  • 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).
  • GET /threads — same parameters as /messages, one entry per conversation: {id, mailbox, latest: <message summary>}.
  • GET /threads/{id} — {id, mailbox, messages:[summary…]}, oldest first, limited to what the caller may see. Threads are per mailbox.

# 8.3 Incremental sync — GET /messages/changes

Per mailbox (?address=, required when the caller can read several).

text
GET /messages/changes                      → { mailbox, state: "st_…", created: [], updated: [], destroyed: [], has_more: false }
GET /messages/changes?since=st_…&limit=200 → { mailbox, state: "st_… (new)", created: ["msg_…"], updated: ["msg_…"], destroyed: ["msg_…"], has_more }

Bootstrap: 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).

# 8.4 Folders

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).


# 9. Modifying messages

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)
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
DELETE /messages/{id} moves to Trash → {ok:true, permanent:false}
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}

# 10. Drafts and files

# 10.1 Drafts

POST /drafts same body as /messages/send without send_at/draft; only from is required → 201 {status:"draft", id:"msg_…"}
GET /drafts?address=&limit=&cursor= drafts of the readable mailboxes
GET /drafts/{id} full message
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)
DELETE /drafts/{id} destroys the draft (409 draft_in_use if it backs a scheduled or pending send)
POST /drafts/{id}/send { "send_at"? } — same checks and outcomes as /messages/send; 409 draft_in_use if already being sent

Draft HTML is sanitised when stored: what the webmail later displays is never the caller's raw HTML.

# 10.2 Files

bash
curl -X POST "$BASE/files?filename=rapport.pdf&address=contact@spboucher.ai" \
  -H "Authorization: Bearer $KEY" -H 'Content-Type: application/pdf' --data-binary @rapport.pdf
# 201 → { "id": "file_…", "name": "rapport.pdf", "type": "application/pdf", "size": 30000, "mailbox": "contact@spboucher.ai", "expires_at": "…" }

Raw 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.

# 10.3 Attachments of received mail

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.


# 11. Webhooks and events

# 11.1 Managing

POST /webhooks { name, url, events:[…], address_ids?:[uuid], include_content? (false), active? (true) } → 201, with secret (whsec_…) shown once
GET /webhooks, GET /webhooks/{id} a key sees only its own webhooks; an administrator session sees all
PATCH /webhooks/{id} any creation field, plus rotate_secret: true (returns the new secret once; sessions need re-authentication)
DELETE /webhooks/{id} also removes its delivery history
GET /webhooks/{id}/deliveries?status=&limit=&cursor= attempts, newest first: `{id, event_id, event_type, status: pending
POST /webhooks/{id}/test sends a signed webhook.test event now → {delivery, http_status, error}
POST /webhook-deliveries/{id}/replay queues the delivery again (same event id, new timestamp and signature, attempt counter reset)
GET /events?type=&limit=&cursor= recent events visible to the caller, newest first, metadata only (never subject/preview), kept 30 days

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.

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).

# 11.2 Events

Type Emitted when data
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)
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}]
message.delivered / message.deferred / message.bounced / message.failed the overall status of an API send changed to that value (§7) same as message.sent
message.read a tracked received message got the read flag message_id, thread_id, address
message.deleted a tracked received message was moved to Trash (permanent:false) or destroyed (permanent:true) message_id, address, permanent
draft.created a draft was created through the API message_id, from, to[]
address.created an address was created through the API address_id, address, kind
address.suspended an address was suspended (reason: "suspended") or expired (reason: "expired") address_id, address, reason
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)

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.

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}.

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.

# 11.3 Delivery

POST <url> with the JSON payload:

json
{ "id": "evt_Qm1…", "type": "message.received", "occurred_at": "2026-11-19T06:04:19.412Z",
  "address": "alerts@spboucher.ai", "mailbox": "notifications@spboucher.ai",
  "data": { "message_id": "msg_…", "thread_id": "thr_…", "address": "alerts@spboucher.ai", "from": ["a@example.org"], "to": ["alerts@spboucher.ai"], "cc": [],
            "delivered_to": ["alerts@spboucher.ai"], "received_at": "2026-11-19T06:04:18Z", "size": 3412, "has_attachment": false, "folders": ["inbox"] } }

Headers: SPMail-Signature, SPMail-Event-Id, SPMail-Event-Type, SPMail-Delivery-Attempt (1, 2, …), User-Agent: SPMail-Webhooks/1, Content-Type: application/json.

  • Success = any 2xx within 10 s. The response body is ignored (at most 64 kB are read).
  • 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.
  • 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.

# 11.4 Verifying the signature

text
SPMail-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, t + "." + raw request body)>

Compute 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).

js
// Node
import crypto from "node:crypto"
function verify(secret, header, rawBody, toleranceSec = 300) {
  const m = /^t=(\d+),v1=([0-9a-f]{64})$/.exec(header ?? "")
  if (!m) return false
  if (Math.abs(Date.now() / 1000 - Number(m[1])) > toleranceSec) return false
  const expected = crypto.createHmac("sha256", secret).update(`${m[1]}.${rawBody}`).digest()
  const given = Buffer.from(m[2], "hex")
  return given.length === expected.length && crypto.timingSafeEqual(given, expected)
}
// express: app.post("/hook", express.raw({ type: "application/json" }), (req, res) => {
//   if (!verify(SECRET, req.get("SPMail-Signature"), req.body.toString("utf8"))) return res.sendStatus(400)
//   const event = JSON.parse(req.body); /* dedupe on event.id */ res.sendStatus(204) })
python
# Python
import hashlib, hmac, re, time
def verify(secret: str, header: str, raw_body: bytes, tolerance: int = 300) -> bool:
    m = re.fullmatch(r"t=(\d+),v1=([0-9a-f]{64})", header or "")
    if not m or abs(time.time() - int(m.group(1))) > tolerance:
        return False
    expected = hmac.new(secret.encode(), m.group(1).encode() + b"." + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, m.group(2))

# 12. Introspection

  • GET /health (public) → {ok, version, database: "ok"|"down", mail_server: "reachable"|"unreachable", workers: "on"|"off"}; 503 when not ok.
  • GET /me →
json
{ "type": "key", "id": "…", "name": "agent-alertes", "explorer": false, "scopes": ["mail.read", "mail.send"], "all_addresses": false,
  "addresses": [ { "id": "…", "address": "alerts@spboucher.ai", "kind": "alias", "mailbox": "notifications@spboucher.ai", "status": "active", "can_send": true, "can_receive": true, "read": "restricted" } ],
  "limits": { "rate_per_minute": 60, "daily_send_limit": 200, "external_send_policy": "approval", "allowed_recipient_domains": [] },
  "usage_today": { "sent": 3, "requests": 41 }, "version": "…" }

read is full, restricted or none (see §4). For a session: type: "user", limits null/allow.

  • GET /openapi.json, GET /openapi.yaml (public) — OpenAPI 3.1; each operation lists its scopes in x-required-scopes.

# 13. Administration (session only)

Under /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.

API keys

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
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
PATCH …/{id} ⟳ same fields; effective at the key's next request
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
DELETE …/{id} immediate revocation (also kills its explorer tokens)
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}]}
POST …/{id}/explorer-token 201 {token: "spx_…", expires_at, key_id, purpose: "explorer"}

The 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.

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.

Webhook internal allowlist — GET /api/admin/webhook-allowlist · POST ⟳ {host_port: "127.0.0.1:9000", note?} · DELETE ?host_port= ⟳.

Scheduled messages — GET /api/admin/scheduled · DELETE /api/admin/scheduled/{id}.

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}.

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).

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).

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.


# 14. Limits and what is not supported

Limits

JSON body 1 MB; 6 MB on composing routes
File upload 50 MB per file; ≤ 30 attachments per message
Recipients ≤ 100 per message; batch ≤ 50 messages
Scheduling ≤ 30 days ahead
Page size ≤ 100
Custom headers ≤ 20, values ≤ 900 chars
Message bodies returned 1 MB per part (truncated: true beyond)
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

Not supported / honest caveats

  • 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.
  • 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).
  • message.read / message.deleted are best effort (§11.2). Messages destroyed that the watcher never tracked produce no event.
  • Reception is detected by polling (default 5 s), not by a push stream.
  • multipart/form-data uploads are not parsed; POST /files is not idempotent.
  • Sorting is newest-first only.
  • Threads are per mailbox; in address-restricted views threads are collapsed per page (a conversation may reappear on a later page).
  • PATCH /drafts/{id} returns a new id.
  • 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.
  • Quota and retention apply to physical mailboxes, not to individual aliases.
  • 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.
  • 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.
  • 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.
  • 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.
  • 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.
  • 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.
  • No sending to distribution lists by name, no templates, no open/click tracking (by design).

# 15. Error codes

HTTP Codes
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
401 unauthenticated, invalid_api_key, key_revoked, key_expired
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
404 not_found (unknown or not visible to the caller — deliberately indistinguishable)
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
413 payload_too_large, file_too_large
415 multipart_not_supported, unsupported_media_type
429 rate_limited, daily_send_limit_exceeded
500 internal
502 mail_server_unavailable, mail_server_error
503 (GET /health only)

# 15b. Templates (send by template)

Templates 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.

Endpoint Scope Purpose
GET /templates mail.send or mail.drafts List templates (no HTML)
GET /templates/{id} same Template with html and text
POST /templates/{id}/render same {variables, use_examples?} → {subject, preheader, html, text, missing}; nothing is sent
POST /messages/send with template_id mail.send Send the rendered template
json
POST /api/v1/messages/send
{
  "from": "notifications@spboucher.ai",
  "to": [{ "email": "recette@stg.spboucher.ai" }],
  "template_id": "6f1c0c1e-…",
  "variables": { "first_name": "Zoé", "code": "424242", "action_url": "https://wallet.spboucher.ai/verify" }
}

Rules: 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.

# 16. Clarifications (2026-11-19, found while building the SDKs)

  • 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).
  • Search — subject, from, to and text filters match whole words (the mail server's full-text index), not arbitrary substrings.
  • 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.
  • Drafts — POST /drafts returns the full outbound-shaped object with status: "draft", as in the OpenAPI document.
  • Validation errors are 400; the API never answers 422.
  • 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": […] }.
  • 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.
Files main
Menu

Theme