Mail relay: docs, agent guide, skills, changelog draft; test against the real service code; starter offers the mail service

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-25 20:53:38 +01:00
co-authored by Claude Fable 5.2
parent 533f571d4d
commit dd3792cbc7
25 changed files with 991 additions and 167 deletions
+426 -118
View File
@@ -1,12 +1,352 @@
# email
Sending mail with two transports to choose from: **SMTP from the panel**
(`panelSmtpAdapter`, universal) or **Microsoft Graph** (`graphAdapter`,
through Exchange/M365). Both implement the same `PayloadEmailAdapter` interface,
so `payload.sendEmail` and form mail work whatever the choice.
The project wires the adapter in `buildConfig({ email })` (the recommended dispatcher is `mailAdapter()`),
and the editor picks the transport in the panel. A separate `sendEmail` helper (from `/server`) sends
**always through the SMTP** from the panel, bypassing the adapter.
Mail works with **no setup**: a site with no SMTP server in the panel sends through the
**Intecion Notifications Webservice** (below: "the mail service"), from
`[email protected]`, under the site's own sender name. Two more transports exist:
| Transport | When | Sender address |
|---|---|---|
| **The mail service** (`relayAdapter`, inside `mailAdapter()`) | the default — nothing filled in | `[email protected]`; replies go to the panel's "Sender address" |
| **SMTP from the panel** (`panelSmtpAdapter`) | on the client's request: its own mail server, its own sender address | the panel's "Sender address" |
| **Microsoft Graph** (`graphAdapter`) | **deprecated since 1.17.0, removed in 2.0** — sites that have the `GRAPH_*` variables | `GRAPH_SENDER` |
All three implement Payload's `PayloadEmailAdapter`, so `payload.sendEmail`, form mail, password reset and
account verification work whatever the transport. The project wires **one** adapter,
`buildConfig({ email: mailAdapter() })`; which transport a send takes is decided on every send.
A separate `sendEmail` helper (from `/server`) sends **always through the SMTP** from the panel.
## Wiring
```ts
// payload.config.ts
import { iapl, mailAdapter } from '@intecion/ipal-kit'
export default buildConfig({
serverURL: process.env.NEXT_PUBLIC_SERVER_URL, // the site's public address: the mail service calls it back
email: mailAdapter(),
plugins: [iapl({ /* mail: { relay: … } — only to change a default, see "Options" */ })],
})
```
The plugin does **not** set `config.email` — without `email:` Payload uses a mock that only logs to the console.
## Which transport a send takes
Decided on every send from Site integrations → E-mail sending, with no stored value of its own
(`resolveMailTransport(settings, { graphEnv, relay })` returns `'graph' | 'smtp' | 'relay' | 'none'`, type `MailTransport`):
1. "Sending method" is Microsoft Graph **and** the four `GRAPH_*` variables are set → **Graph**, as before (deprecated).
2. The panel has an SMTP server (server, user name and password) → **SMTP**.
3. The four `GRAPH_*` variables are set → **Graph** (deprecated), until they are removed.
4. Otherwise → **the mail service**, unless it is switched off (`mail: { relay: false }`).
5. Otherwise nothing is configured: the send reports `{ sent: false, code: 'not-configured' }`, as before 1.17.0.
- **A site with SMTP filled in never contacts the mail service.** Nothing changes for it.
- **SMTP on the client's request:** an admin fills in "Own SMTP server", user name and password; from the next send
the site uses the client's server and the client's own sender address. Emptying the server returns the site to
the mail service.
- There is **no fallback** from a failing SMTP server to the mail service: a client who asked for its own server
gets no mail from another address.
- "Sending method" keeps its two stored values (`smtp`, shown as "Automatic", and `graph`); no field was added.
## The mail service
A service run by Intecion that sends mail for its clients' sites. A site holds **no mail key and no
password**: it gets its own token by proving that it is served at its host. Nothing is typed anywhere.
### The first send (enrolment)
1. The site makes a random nonce, keeps its hash for 5 minutes and calls
`POST https://webservices.intecion.net/mail/v1/enrol` with `{ host, nonce, product: 'iapl', productVersion }`.
**This is the first outbound call: it carries the site's host and the plugin version, nothing else.**
2. Before it answers, the service calls the site back:
`POST https://<host>/api/iapl/mail-relay/confirm` with the nonce and a token.
3. The site's confirm route accepts the call only when it holds exactly that nonce, stores the token and answers
with a hash of both. Only then does the token become valid.
4. The message is sent. Later sends skip all of this.
What the site needs for it:
- **`serverURL`** in the Payload config, with the public host the site really answers on (`https://example.com`,
not a host that redirects to `www`). Another host: `mail: { relay: { host: 'www.example.com' } }`.
- **The confirm route reachable from the internet**, at exactly `/api/iapl/mail-relay/confirm`, over HTTPS on port
443, **without a redirect** — the service follows none. No basic auth, no firewall rule, no maintenance page in
front of it. (Coolify: nothing to set; the route is part of Payload's API.)
- **Outbound HTTPS** from the server to `webservices.intecion.net`.
- A host Intecion has **listed** is active at once. Any other host is enrolled but **waits for approval**: mail is
not sent until Intecion approves it, then the same token works. The panel says which it is.
A site on `localhost`, on a private address or without `serverURL` is refused **by the plugin itself**, before any
call leaves the server — development machines do not contact the service. To test mail locally use SMTP (a local
catcher such as Mailpit) or the fake service ("Testing").
### What leaves the server
- At enrolment: the host and the plugin version.
- With every message: recipients, subject, text and HTML, attachments, the sender name, the reply address, the
kind of the message, and an idempotency key. The service keeps a log of metadata only (no subject, body,
attachment, reply address or recipient address) for 30 days.
- The service adds `X-Intecion-Site: <host>` and `X-Intecion-Product: iapl` to every mail.
- Recipients' addresses and message bodies pass through Cloudflare (the service's mail back end). Name it in the
client's processing agreement before a client site sends through the service.
### Sender name and reply address
- **Sender name:** `mail.relay.senderName`, else the panel's "Sender name", else the site name from Site
settings; with none of them the mail leaves under the site's host (`relaySenderName(payload, options, panelName)`).
- The service checks the name: at most 64 characters, letters of one script, no address, no name of a mailbox
provider, bank or "support". **A name it does not accept is not a failed send** — the mail leaves under the
site's host, the result carries `warnings: ['sender-name-replaced']`, and the panel's state block shows the name
that was used so the client can choose another. The check errs on the careful side and can replace an honest
name that reads like a web address ("Dom.Pl").
- **Reply address:** the message's own `replyTo` (a form sets one), else the panel's "Sender address". The
service's sender address has no mailbox: **fill in "Sender address"**, or replies are lost (the doctor warns:
`mail-reply-address`).
- `from` and free headers of a message are ignored: the service fixes the sender address and takes no header.
### Limits
The numbers are the service's, per site, and can be changed by Intecion for one site. Defaults:
| Limit | Default | Applies to |
|---|---|---|
| Messages an hour / a day | 30 / 200 | everything but security alerts; mail other than account mail may use four fifths (24 / 160) |
| Recipients a message | 10 | To, CC and BCC together |
| Confirmations to one address a day | 10 | a form's confirmation to an address a visitor typed |
| New addresses a day | 50 | addresses the site has not written to for 30 days |
| Files in one message | 10 MB, 20 files | read by the plugin from the service; programs and scripts are refused |
| Text and HTML together | 500 kB | |
A message over a limit is refused whole (`relay-quota`, `relay-too-large`); the site is not suspended for it.
`mailAttachmentLimit(payload)` reports the file limit the service named, so a form's File field never promises
more ([forms.md](./forms.md) "Files"); until the site has enrolled it is `null` (the plugin has no number of its own).
**Account mail is limited by the site itself.** "Forgot password" is a visitor's lever like a form, and the
service lets account mail use the whole hour. So the relay transport holds back more than **5 account e-mails to
one address** and more than **10 asked for by one visitor** within an hour (`mail.relay.accountMail`:
`{ perAddress, perVisitor, windowMinutes }`, or `false`). A held-back message is reported as `relay-quota` in the
log and the panel; the visitor is told nothing. Pin the address header for it: `IAPL_IP_HEADER`
([security.md](./security.md)).
### What a message is (kinds)
The service limits kinds differently, so every message says what it is — truthfully:
| Kind (`MailKind`, list: `MAIL_KINDS`) | Who sets it |
|---|---|
| `form-notification` | the plugin: a form's e-mail whose every recipient is an address written in the panel |
| `form-confirmation` | the plugin: a form's e-mail to an address a visitor typed (`buildFormMailKindHook`) |
| `account` | the plugin: Payload's "forgot password", and "verify your e-mail" where the collection verifies addresses |
| `test` | the plugin: the test e-mail from the panel |
| `security-alert` | nothing yet. The service addresses these itself (to Intecion); recipients are ignored |
| `system` | everything else: mail whose purpose is not known, your own `payload.sendEmail` |
Your own mail:
```ts
import { runWithMailKind, withMailKind } from '@intecion/ipal-kit'
// one message
await payload.sendEmail(withMailKind({ to, subject, html }, 'account')) // an invitation to an account holder
// everything sent inside
await runWithMailKind('account', () => sendWelcomeMails(payload, user))
```
- `mailKindOf(message)` reads the mark (the key is the symbol `MAIL_KIND`; other transports ignore it).
- `mail.relay.kind: (message) => MailKind | undefined` decides for messages nobody marked.
- `expectMailTo(address, kind, { visitor })` says what the **next** message to one address is, for mail a library
composes by itself; the plugin uses it for Payload's account mail. It lasts ten seconds and one message.
- Mark `account` only for mail to an account holder, and `form-confirmation` for mail to an address a visitor typed.
A wrong kind gives a visitor room the service did not mean to give.
### Retry, and "not confirmed"
- A message is encoded **once**; exactly those bytes go out on every attempt, under one `Idempotency-Key`. At most
**three attempts**, 30 seconds each, at most ten seconds of waiting between them in all — and only after an answer
the service marks retryable, or after no answer. An enrolment on the way is not one of the three.
- **No answer at all** (time-out, connection lost) is reported as `relay-not-confirmed` with `confirmed: false`: the
message **may have been sent**. Sending the same message again within 24 hours reuses the same key, so the
service answers with what happened to the first attempt (`replayed: true`) and no second mail goes out.
- The form **keeps working** meanwhile — the submission is saved in Form Submissions; only the mail is missing.
- There is no stored outbox: a message that failed is not sent later by itself.
### The token
- Kept in Payload's key-value store (`payload.kv`, the `payload-kv` collection Payload itself adds; key
`RELAY_KV_KEY` = `iapl:mail-relay`). **No field, no column, no migration.** That collection refuses every
operation through access control and is hidden in the panel, so the token cannot be read over REST or GraphQL —
not by an admin either. It is never logged and never sent to a browser.
- The token works only from the server addresses the site enrolled from. After a move to another server the
service answers "enrol again"; the site does, by the same call-back, and sends. A site whose requests leave from
many changing addresses (serverless, a pool of egress addresses) needs its limit of addresses raised by Intecion.
- **Rotation:** every 90 days the service says the token is due; the site asks for a new one before its next send
and stores it at once. The previous token works for 24 hours more, so several containers of one site do not cut
each other off (they share the database). `rotateRelayToken(payload)` does it now.
- **A lost token heals itself:** the next send enrols again.
- **Disconnect:** "Disconnect" in the panel (`disconnectRelay(payload)`) gives the token up on the service and stops
the site from enrolling by itself until "Connect again" (`enrolRelay(payload, { force: true })`).
- **A token issued by hand** — for a site the service cannot call back (behind a firewall): Intecion issues one,
an admin enters it in the state block ("Enter an access key"), or a script calls `setRelayToken(payload, token)`.
- Encryption at rest: none, like `smtpPassword`. A token read from a database dump is of little use — it does not
work from another server address.
### The state block in the panel
Site integrations → E-mail sending starts with "How e-mails are sent" (component `MailRelayStatus`, import-map
entry `@intecion/ipal-kit/admin#MailRelayStatus` — **run `payload generate:importmap` after upgrading**): the
transport in effect; for the mail service the state (connected, waiting for approval, stopped, not connected and
why), the address mail leaves from, where replies go, what is left of the hour and the day, and a sender name the
service replaced. Buttons: **Check now**, **Connect again**, **Disconnect**, **Enter an access key**.
Routes (all three need the `admin` role: not logged in → 401, other role → 403; none ever answers with a token):
| Route | What |
|---|---|
| `GET /api/iapl/mail-relay/status` | the transport and the stored state; `?refresh=1` asks the service |
| `POST /api/iapl/mail-relay/connect` | enrol now; with `{ token }` store a token issued by hand |
| `POST /api/iapl/mail-relay/disconnect` | give the token up |
| `POST /api/iapl/mail-relay/confirm` | **public** — the service's call-back. `404` and no change unless the site itself started an enrolment in the last 5 minutes; rate-limited (10 a minute per address, `mail.relay.confirmRateLimit`) |
These are the first routes under `/api/iapl/`; the others stay under `/api/ipal/` until 2.0. The confirm path is
fixed by the service for this product — a project cannot move it. For your own panel:
`relayPanelEndpoints()`, `mailPanelState(req, undefined, { refresh })` (type `MailPanelState`), `getRelayStatus(payload, { refresh })`
(type `RelayStatus`).
### Status codes
`mailAdapter()` records a failed send in `emailStatus` (banner on the tab, alert on the dashboard). The codes of
the mail service (`RELAY_STATUS_CODES`, type `RelayStatusCode`; `relayStatusFor(code, retryable)` maps a code of
the service), each with a text in the editor's language:
| Code | Meaning | What to do |
|---|---|---|
| `relay-pending` | enrolled, waiting for approval by Intecion | Intecion approves the host; nothing to do on the site |
| `relay-suspended` | stopped by Intecion | contact Intecion; SMTP in the panel sends meanwhile |
| `relay-refused` | the site could not enrol | "When the site cannot be confirmed" below |
| `relay-disconnected` | an admin pressed "Disconnect" | "Connect again", or fill in SMTP |
| `relay-quota` | a limit of the site or of the whole service; too many recipients; the site's own limit on account mail | wait; ask Intecion for other limits; SMTP for a site that sends more |
| `relay-too-large` | text or files over the service's limit | a smaller file; `forms.attachments.maxFileSize`; SMTP |
| `relay-attachment-refused` | a file type the service never carries (programs, scripts), or a bad file name | send without that file |
| `relay-recipient-suppressed` | the back end refuses one recipient (its mailbox bounced or complained before, for any site). Nothing was sent to anybody | correct the address; ask Intecion to clear it |
| `relay-unreachable` | the service or its back end failed or could not be reached; "probably not sent" | try again; if it persists, SMTP |
| `relay-not-confirmed` | no answer: the message may have been sent | check the mailbox before sending again |
| `relay-error` | the service refused the request as wrong, or the message has no recipient or body | a bug: report it with the server log |
| `relay-name-replaced` | (a warning in the state block, not a failure) the sender name was replaced | choose another "Sender name" |
The result of a send through the service (`RelaySendResult`): `{ sent: true, transport: 'relay', id, messageId?, kind, replayed, senderName, warnings }`
or `{ sent: false, transport: 'relay', code, cause, confirmed, error, detail }` — `cause` is the service's own
code, `detail` is for the log and the panel, never for a visitor.
### When the site cannot be confirmed
`relay-refused` with the cause `callback-failed` and a reason:
| Reason | Usual cause | Fix |
|---|---|---|
| `unreachable`, `timeout` | a firewall, a private network, the wrong public host | open the route, or set `serverURL` / `mail.relay.host` to the host the site answers on; a site that cannot be reached at all gets a token by hand |
| `redirect` | `trailingSlash: true` in `next.config`; `example.com` redirecting to `www.example.com`; a redirect by language | enrol the host that answers without a redirect; for trailing slashes ask Intecion to set the path ending in `/confirm/` |
| `status` | the route is missing, blocked, or the API is served at another path (`routes.api`) | ask Intecion to set this site's confirm address; check that no proxy rule blocks `/api/iapl/` |
| `confirmation` | something prints around the JSON answer (a proxy that rewrites responses) | take it out of the way for this route |
After a refusal the site does not ask again by itself for 15 minutes (a call-back that times out costs 8 seconds a
message); "Connect again" asks at once. Other causes: `host-not-allowed` (not a public DNS name),
`enrolment-closed` (the service takes no new sites).
### Options
`iapl({ mail: { relay } })` (`MailOptions`, `RelayOptions`); `mailAdapter({ relay })` overrides it for that adapter
(`resolveRelayOptions(payload, own)` gives the options in effect).
| Option | Default | What |
|---|---|---|
| `relay: false` | — | switches the mail service off: no enrolment, no outbound call, no confirm route, no state block, the panel wording of 1.16 |
| `url` | `RELAY_BASE_URL` (`https://webservices.intecion.net/mail`) | another base address — a relay of your own that speaks the same contract |
| `host` | host of `serverURL` (`relayHost(payload, options)`) | the public host the service calls back |
| `enrol` | `'auto'` | `'manual'`: only "Connect again" or `enrolRelay()` enrols. `false`: never (the token comes from `token` or `setRelayToken`) |
| `token` | — | a token from elsewhere (`string` or a function): the stored token is not used and the site does not enrol |
| `senderName` | panel, then site name | a fixed name, or a function |
| `kind` | — | the kind of a message nobody marked |
| `accountMail` | `{ perAddress: 5, perVisitor: 10, windowMinutes: 60 }` | the site's own limit on account mail; `false` = none |
| `confirmRateLimit` | `{ max: 10, windowMs: 60000 }` | calls to the public confirm route per address |
| `timeoutMs` | `30000` | one attempt of a send |
| `retryBackoffMs` | `1000` | the wait before the next attempt when the service names none (times the attempt's number) |
| `fetchImpl` | `fetch` | for tests |
| `graphDeprecationWarning` (on `mail`) | `true` | `false` silences the start warning of a site on Microsoft Graph |
Fixed values are in `RELAY_DEFAULTS`; `RELAY_CONTRACT_VERSION` is the version of the wire contract the client
speaks, `RELAY_PRODUCT` its product name (`iapl`), `RELAY_SERVICE_NAME` the service's name, `RELAY_CONFIRM_PATH`
the confirm path under the API route, `RELAY_SENDER_ADDRESS` the sender address until the service has been asked.
### Turn off, your own relay, the transport alone
- **Off:** `iapl({ mail: { relay: false } })`. The site then sends only through SMTP (or Graph), as before 1.17.0.
Use the plugin option, not only `mailAdapter({ relay: false })`: the option also removes the routes and the state block.
- **A relay of your own:** `mail: { relay: { url, token: () => process.env.MY_RELAY_TOKEN, enrol: false } }`, or
keep the call-back enrolment if your relay speaks it. The wire format is the contract copied in the repository
(`contracts/mail-relay/`), typed as `RelaySendRequest`; `buildRelayMessage(message, { kind, senderName, replyTo })`
(`BuildRelayMessageArgs`, `BuiltRelayMessage`) builds a request from a Payload message, `bareAddress` /
`bareAddresses` and `cleanSubject` are its parts, `relayRequest(call)` (`RelayCall`, `RelayAnswer`,
`RelayRefusal`) is one HTTP call, `sendThroughRelay(payload, options, message, context)` (`RelaySendContext`)
one message with the retry rule, `isPublicHost(host)` the check of a host.
- **The transport alone:** `email: relayAdapter()` (`RelayAdapterArgs`) — the mail service and nothing else, with the
panel's sender name and reply address when Site integrations exists. `relayAttachmentLimit(payload, options)` is
its file limit.
- **The confirm route alone:** `relayConfirmEndpoint()`, for a project that builds its own config without `iapl()`.
- **Your own e-mail adapter:** `email:` in `buildConfig` is the project's and wins over everything here ("Your own
e-mail adapter" below).
### Testing
`createFakeRelay()` is the service in memory (`FakeRelay`, `FakeRelayOptions`, `FakeRelayMail`,
`FakeRelayLimits`): it speaks the contract — every example of the contract runs against it in the plugin's own
tests — and records accepted mail instead of sending it.
```ts
import { createFakeRelay, mailAdapter } from '@intecion/ipal-kit'
const relay = createFakeRelay({ allow: ['example.com'], callSite: (url, init) => myApp.fetch(url, init) })
// config: email: mailAdapter({ relay: { url: relay.url, fetchImpl: relay.fetch } })
await payload.sendEmail({ to: '[email protected]', subject: 'Hi', html: '<p>Hi</p>' })
expect(relay.outbox[0]).toMatchObject({ kind: 'system', to: ['[email protected]'] })
```
- `allow` / `relay.allow(host)`: hosts that are active at once; others wait for approval. `relay.setSite(host, state)`,
`relay.issueToken(host)`, `relay.backend = 'failure'`, `relay.intercept`, `relay.limits`, `relay.clientAddress`
arrange what a test needs; `relay.listen(port)` serves it over HTTP for a site in another process
(`allowLocalHosts: true` lets it call back `http://localhost:<port>`).
- It is **not** the service: its sender-name check and its limits are simplified. Test what the site does with each
answer, not what the service accepts.
## SMTP — on the client's request
The panel's SMTP fields (`smtpHost`, `smtpPort` (default 587), `smtpUser`, `smtpPassword`, `smtpFromAddress`,
`smtpFromName`) and `emailTransport` live in Site integrations (E-mail sending tab). Filling in server, user name
and password switches the site to the client's server.
- **The password is write-only and stays with its server**: the panel shows "A value is set"; changing the
server, port or user name asks for the password again ([security.md](./security.md) "Stored secrets").
- The address and name from the panel always win over the message's `from`. CR/LF characters are stripped from the
subject (protection against header injection through form-builder `{{field}}`).
- Missing SMTP config or a send error → the adapter **does not throw**, it returns `{ sent: false, error }` and logs.
- Port 465 → implicit TLS, others → STARTTLS.
- The adapter reads the config on every send, so changing the mailbox in the panel works without a restart.
SMTP only, without the dispatcher:
```ts
// payload.config.ts
import { panelSmtpAdapter } from '@intecion/ipal-kit'
export default buildConfig({
email: panelSmtpAdapter(),
// panelSmtpAdapter({ fallbackFromAddress, fallbackFromName }) — used only
// before the panel is filled in (Payload needs the address synchronously at
// startup, before the global can be read)
})
```
Options: `fallbackFromAddress` (`'noreply@localhost'`), `fallbackFromName` (`'Website'`).
## Dependency
@@ -20,18 +360,7 @@ install it (nodemailer 10 ships its own types, so `@types/nodemailer` is not nee
- **Since nodemailer 9**, attachments given as an `href`/`path` URL are fetched with TLS certificate validation.
A mail with an attachment from a host with a self-signed certificate now fails instead of sending.
## Config
No plugin options — SMTP (`smtpHost`, `smtpPort` (default 587), `smtpUser`,
`smtpPassword`, `smtpFromAddress`, `smtpFromName`) and `emailTransport` live in
SiteIntegrations (E-mail sending tab). The editor configures them in the panel.
- **The password is write-only and stays with its server**: the panel shows "A value is set"; changing the
server, port or user name asks for the password again
([security.md](./security.md) "Stored secrets"). The plugin does **not** set
`config.email` — you wire the adapter yourself (below).
## Front — sendEmail (server)
## The sendEmail helper (server)
```ts
import { sendEmail } from '@intecion/ipal-kit/server'
@@ -63,46 +392,11 @@ if (result.sent) {
- Port 465 → implicit TLS, others → STARTTLS.
- `server-only` — the SMTP password never ends up in the browser bundle.
## Note: Payload system mail
## Payload system mail
Password reset / email verification go through Payload's built-in mechanism
(`config.email`), which the plugin does **not** set by itself. Wire
`mailAdapter()` / `panelSmtpAdapter()` in `buildConfig({ email })` (below) — then
this mail also goes through the mailbox from the panel, with no SMTP in env.
## Adapter — SMTP from the panel for all of Payload
`sendEmail` sends with its own transport. Separately, the plugin provides an adapter that
connects the same mailbox to `payload.sendEmail`:
`mailAdapter()` is recommended (below, "Wiring — choosing the transport") — it contains this
adapter and adds Graph. SMTP only:
```ts
// payload.config.ts
import { panelSmtpAdapter } from '@intecion/ipal-kit'
export default buildConfig({
email: panelSmtpAdapter(),
// panelSmtpAdapter({ fallbackFromAddress, fallbackFromName }) — used only
// before the panel is filled in (Payload needs the address synchronously at
// startup, before the global can be read)
})
```
Options: `fallbackFromAddress` (`'noreply@localhost'`), `fallbackFromName` (`'Website'`).
The address and name from the panel always win over the message's `from`. CR/LF characters are
stripped from the subject (protection against header injection through form-builder `{{field}}`).
Missing SMTP config or a send error → the adapter **does not throw**, it returns
`{ sent: false, error }` and logs.
Once wired, everything in Payload that sends mail goes through the SMTP from Site
Integrations — including the built-in form-builder mail (Forms → Emails), password
reset and account verification mail. The adapter reads the config on every
send, so changing the mailbox in the panel works without a restart.
Without an adapter Payload uses a mock that only logs to the console — form-builder
mail will not go out.
Password reset and e-mail verification go through Payload's built-in mechanism (`config.email`). With
`mailAdapter()` wired they take the same transport as everything else; with the mail service they are sent as
account mail ("What a message is").
## Masking secrets in the panel (MaskedField)
@@ -121,10 +415,31 @@ Works on any `text` field. After wiring it in a project you may need
> database protection — if the DB leaks, the secrets are readable.
## Adapter — Microsoft Graph (Exchange / M365)
## Microsoft Graph (Exchange / M365) — deprecated
Alternative to SMTP: sending through the Microsoft Graph API, through a mailbox in
your (agency) M365 tenant. All form mail from all
> **Deprecated since 1.17.0; removed in 2.0** (with Payload 4). It keeps working, unchanged, in every 1.x release.
> Nothing new is built on it. A site on Graph prints one warning at start (`GRAPH_DEPRECATION_NOTICE`; silence:
> `mail: { graphDeprecationWarning: false }`) and the doctor reports `mail-graph-deprecated`. `graphAdapter`,
> `GraphAdapterArgs` and `mailAdapter({ graph })` are marked `@deprecated`.
### Moving off Microsoft Graph
To the mail service (when the owner says so):
1. Upgrade; check that `serverURL` is the site's public address.
2. Intecion lists the host on the service (or approves it after the first send).
3. Remove the four `GRAPH_*` variables in Coolify and redeploy. If "Sending method" says Microsoft Graph, set it
to "Automatic".
4. Site integrations → E-mail sending → send a test e-mail: the answer says "through the built-in mail service".
5. Check "Sender name" and "Sender address" (now the reply address), and tell the client that mail now comes from
`[email protected]` instead of the present mailbox (allow-lists, filters).
Going back is putting the variables back. To SMTP instead: fill in the SMTP fields, send a test, remove `GRAPH_*`.
A project that wants Graph after 2.0 brings its own adapter ("Your own e-mail adapter"): the 1.x Graph adapter
is two files of plain `fetch` that can be copied.
Sending through the Microsoft Graph API, through a mailbox in your (agency) M365 tenant. All form mail from all
projects goes through ONE sender mailbox (e.g. `[email protected]`).
### Config split (deliberate)
@@ -147,23 +462,6 @@ Options `graphAdapter({ fallbackFromAddress, fallbackFromName, largeAttachments,
the first two are placeholders Payload requires at startup; the other two are for attachments ("Attachments" below).
`fetchImpl` is for tests.
### Wiring — choosing the transport (recommended: `mailAdapter`)
```ts
// payload.config.ts
import { mailAdapter } from '@intecion/ipal-kit'
email: mailAdapter(), // SMTP or Graph — chosen in the panel, on EVERY send
```
`mailAdapter` is a dispatcher: it reads `emailTransport` from Site integrations on every
send (no value → `'smtp'`), so the switch in the panel works without a restart.
Graph only when all 4 `GRAPH_*` variables are in env — otherwise a clear log and
fallback to SMTP (mail is not lost silently).
Options: `fallbackFromAddress`, `fallbackFromName` (for both delegates), `smtp`
(`PanelSmtpAdapterArgs`), `graph` (`GraphAdapterArgs`).
Low-level (when the transport should be fixed in the config):
```ts
@@ -198,10 +496,18 @@ to the client's address. The OAuth token is cached in the process until a minute
## Attachments
`payload.sendEmail({ …, attachments: [{ filename, content: Buffer, contentType }] })` works on both transports
`payload.sendEmail({ …, attachments: [{ filename, content: Buffer, contentType }] })` works on every transport
(nodemailer's shape). Form files use it: a file a visitor attaches is e-mailed and never stored
([forms.md](./forms.md) "Files"). Base64 adds 37 %: a 10 MB file is a 13.7 MB message.
### The mail service
The service names its limit (10 MB in all files of one message, 20 files, unless Intecion set other numbers for the
site); the plugin reads it from the service and `mailAttachmentLimit(payload)` reports it. A message over the limit
is refused before it is uploaded (`relay-too-large`). Programs and scripts are refused by file name
(`relay-attachment-refused`). Content must be a `Buffer` or a string — a stream or a file path is not carried.
The test e-mail's 10 MB file is at the limit: it shows whether the site's limit is the default.
### SMTP
The adapter passes attachments straight to nodemailer; the plugin sets no limit. The limit is the **mail server's**,
@@ -267,36 +573,18 @@ The large path, step by step, and what happens when it fails:
- [ ] A file of 2.9–3.1 MB (both sides of the switch) arrives.
- [ ] Server log after a send: no `delete it by hand`.
## Transport switch — mailAdapter
`mailAdapter()` is a dispatcher: one adapter wired in the config, it picks the transport
(SMTP/Graph) on EVERY send by reading the setting from the panel. That is why
the switch works in the panel (Payload builds the adapter once at startup, so you cannot
swap separate adapters at runtime — the dispatcher delegates internally).
```ts
// payload.config.ts — ONE adapter, the choice happens inside
import { mailAdapter } from '@intecion/ipal-kit'
email: mailAdapter()
```
Panel → Site integrations → E-mail sending → **Sending method** (SMTP / Microsoft Graph).
The dispatcher reads this choice per send. Guard: if Graph is selected but the
secrets are missing in .env → log + fallback to SMTP (no silent failure).
## Test send — button in the panel
The E-mail sending tab has a **Send test** button: enter an address, click, and a test
mail goes out through the CURRENT transport (`payload.sendEmail`). It shows the result (✓/✗ with the error).
Tick **Attach a 10 MB test file** to check that the mail server takes a file of that size ("Attachments" above). Endpoint
The E-mail sending tab has a **Send test e-mail** button: enter an address, click, and a test mail goes out through
the CURRENT transport (`payload.sendEmail`). The answer names the transport ("through the built-in mail service,
as …", "through your SMTP server") and, for the mail service, the sender name that was used. Tick **Attach a 10 MB
test file** to check that a file of that size gets through ("Attachments" above). Endpoint
`POST /api/ipal/test-email`, body `{ to, attachmentMB? }` (`admin` role only — needs roles from the `access` option:
not logged in → 401, other role → 403, bad address → 400, failed send → 502).
not logged in → 401, other role → 403, bad address → 400, failed send → 502 with the reason in the admin's language).
Save your changes before the test — the endpoint reads from the database, not from the field on screen.
> The button shows only the adapter's short error (e.g. `Graph sendMail failed (403).`,
> `Failed to send email.`, `SMTP is not configured…`). The full Graph / SMTP response
> (`ErrorSendAsDenied`, `Insufficient privileges`, `535 …`) is in the **server logs**;
> for SMTP the detail also goes to the status banner (below).
> For SMTP and Graph the button shows only the adapter's short error; the full response (`ErrorSendAsDenied`,
> `535 …`) is in the **server logs**, and for SMTP the detail also goes to the status banner (below).
## Send status in the panel
@@ -304,26 +592,46 @@ Save your changes before the test — the endpoint reads from the database, not
while an error persists, immediately when the state changes). When sending fails:
- **Dashboard** — a red alert with the cause and a link to Site integrations,
- **Site integrations → E-mail sending** — a banner with the error (e.g. `SMTP: connect ECONNREFUSED …`,
`SMTP: SMTP is not configured…`, `SMTP: Invalid login: 535 …`,
`Microsoft Graph: Graph sendMail failed (403).`) and the time.
`SMTP: Invalid login: 535 …`, `Microsoft Graph: Graph sendMail failed (403).`, or the text of a mail service
code from "Status codes") and the time.
Only `mailAdapter` stores the status — `panelSmtpAdapter` / `graphAdapter` alone and
`mailAdapter` and `relayAdapter` store the status — `panelSmtpAdapter` / `graphAdapter` alone and
the `sendEmail` helper do not update it.
The form **keeps working** meanwhile — the submission is saved in Form Submissions,
only the mail did not go out. Graph selected in the panel without `GRAPH_*` in env → warning
"sent over SMTP". Changing the SMTP / transport fields in the panel clears the status; after the next
send (e.g. **Send test**) the current one appears.
only the mail did not go out. Graph selected in the panel without `GRAPH_*` in env and with SMTP filled in →
warning "sent over SMTP". Changing the SMTP / transport fields in the panel clears the status; after the next
send (e.g. **Send test e-mail**) the current one appears.
## Doctor
`iapl-doctor` ([doctor.md](./doctor.md)): `mail-transport` (nothing set up; sending is failing), `mail-relay-state`
(waiting for approval, stopped, refused, disconnected, a replaced sender name), `mail-reply-address`,
`mail-graph-deprecated`, `mail-relay-route` (trailing slashes, another API route, a redirect or a block in front of
the confirm route on the live site).
## Your own e-mail adapter
`email:` in `buildConfig` is the project's. Any Payload adapter works (`@payloadcms/email-nodemailer`, a provider's
SDK); you then skip the panel's SMTP fields, the mail service and the send status. To keep the plugin's parts:
- return `{ sent: false, error, detail? }` instead of throwing, and form files report the failure properly;
- add `attachmentLimit: () => number | null` to the adapter object, and `mailAttachmentLimit(payload)` and the
forms module respect it;
- `recordIntegrationStatus` writes `emailStatus` for the panel's banner;
- `panelSmtpAdapter()` and `relayAdapter()` are whole adapters you can delegate to.
## Turn off, override, extend
- **Turn off:** the plugin does not set `config.email` itself — without `email:` in `buildConfig` Payload uses
its mock (mail only in the console). The SMTP fields in Site integrations and the endpoint
`POST /api/ipal/test-email` are currently always added.
- **Choosing the transport:** `mailAdapter()` (the panel decides) or a fixed `panelSmtpAdapter()` /
`graphAdapter()`; any other Payload adapter (e.g. `@payloadcms/email-nodemailer`) also works —
then you skip the panel SMTP and the send status.
- **Override:** `fallbackFromAddress` / `fallbackFromName`, in `mailAdapter` separately `smtp` and `graph`
(`graph.largeAttachments: false` keeps Graph to attachments under 3 MB — "Attachments").
its mock (mail only in the console). The mail service: `mail: { relay: false }`. The SMTP fields in Site
integrations and the endpoint `POST /api/ipal/test-email` are always added.
- **Choosing the transport:** `mailAdapter()` (decided per send) or a fixed `relayAdapter()` /
`panelSmtpAdapter()` / `graphAdapter()`; any other Payload adapter also works.
- **Override:** `fallbackFromAddress` / `fallbackFromName`; in `mailAdapter` separately `relay`, `smtp` and `graph`
(`graph.largeAttachments: false` keeps Graph to attachments under 3 MB — "Attachments"); every option of the
mail service ("Options"); panel texts through `i18n.translations` (keys `mailRelay…`, `statusEmailRelay…`);
the tab's fields through `integrationsFields`.
- **Extend:** form mail content is modified by `forms.beforeEmail` (see [forms.md](./forms.md));
your own mail — `sendEmail` (SMTP) or `payload.sendEmail` (through the wired adapter).
your own mail — `payload.sendEmail` (through the wired adapter, marked with `withMailKind` when it is not
`system`) or `sendEmail` (always SMTP).