contracts/mail-relay refreshed from IWDL 6cd99f7 (64 files). A token the service knows as another site's is forgotten without revoking and the site enrols as itself; a hand-issued one is refused. The fake requires the header and answers host-mismatch. Co-Authored-By: Claude Fable 5.2 <[email protected]>
689 lines
46 KiB
Markdown
689 lines
46 KiB
Markdown
# email
|
||
|
||
Mail works with **no setup**: a site with no SMTP server in the panel sends through the
|
||
**Intecion Notifications Webservice** — **IWSN** for short, the name the admin panel uses (constant
|
||
`RELAY_SHORT_NAME`); below also "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.
|
||
|
||
**Half an SMTP set-up** (a server and a user name without a password, say) is not an SMTP server: until 1.16 such
|
||
a site refused to send; now its mail goes through the mail service. The server log says so once and the state
|
||
block shows "The SMTP settings below are incomplete".
|
||
|
||
- **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.
|
||
- Every request that carries the token also names the site (`X-Intecion-Site: <host>`): the service refuses a token
|
||
used under another host's name (`403 host-mismatch` — the site then forgets that token and enrols as itself).
|
||
- 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. So an
|
||
**unmarked** mail of your own to the same single address within ten seconds of a "forgot password" that Payload
|
||
did not answer with a mail is counted as account mail; a marked mail (every form mail) never is.
|
||
- 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 of the service** — a time-out, a lost connection, or an answer that is not the service's own JSON (an
|
||
error page of the network in front, a cut-off body) with any status outside 400–499, `200` included — is reported
|
||
as `relay-not-confirmed` with `confirmed: false`: the message **may have been sent**. Such an answer with a status
|
||
from 400 to 499 was turned away before the service handled it: `relay-unreachable`, not sent.
|
||
- **"Not confirmed" is final for that message.** The plugin keeps no unsent mail (no stored outbox), so it does not
|
||
try again by itself after the report. While the same process is running, the same message sent again within
|
||
24 hours goes out under the same key — the service then answers with what happened to the first attempt
|
||
(`replayed: true`) and no second mail goes out. After a restart, or from another instance of the site, a repeat
|
||
(a visitor submitting the form again) is a new message: if the first one did go out, the recipient gets two.
|
||
That is why the panel says "it may have been sent; check the mailbox before trying again".
|
||
- **One budget of time per message:** 10 seconds, 30 with files (`totalTimeoutMs`), for the enrolment, the
|
||
attempts and the waits together — a visitor waits for the form's answer while the mail is sent, and a service
|
||
that hangs must not hold them for the sum of the time-outs. So in practice a hanging service means one attempt.
|
||
- The form **keeps working** meanwhile — the submission is saved in Form Submissions; only the mail is missing.
|
||
- The panel's banner shows the **last** send. A mail that was not sent stays visible in the state block
|
||
("An e-mail was not sent on …", with its code) after later mail went out.
|
||
|
||
### 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 belongs to the host it was issued for.** A store found on another host — a production database
|
||
copied to a staging domain, a site moved to a new domain — is not used: the copy forgets the token (nothing is
|
||
revoked, the other site keeps working), starts unenrolled and enrols as itself, with its own token, limits and
|
||
approval. The start log says so once.
|
||
- 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 })`). It answers
|
||
`{ revoked }`: when the service could not be reached the site stops using the token at once, but the token
|
||
**still works at the service** — the panel says "not confirmed" and keeps it so that "Disconnect" can be pressed
|
||
again; only then is it revoked and forgotten.
|
||
- **A token of another site is refused.** The access-key field asks the service whose token it is before it stores
|
||
anything, and a token stored by a script is checked the same way before its first use (`/v1/status` names the
|
||
host): another site's token is not saved, not used and not revoked.
|
||
- **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)`.
|
||
**Such a site cannot heal by itself:** it never enrols on its own. When the service no longer knows its server
|
||
address (after a move, or a second server) or its token, the send reports `relay-refused` and the state block
|
||
says what to ask Intecion for — the new address added, or a new 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.
|
||
|
||
### Staging and copies
|
||
|
||
- A staging site on its own domain is **its own site** to the service: its own enrolment, token, limits and
|
||
approval ("waiting for approval" until Intecion approves it, unless its host is listed).
|
||
- **A copy of production's database does not carry production's connection.** The stored token is tied to the host
|
||
it was issued for; on another host it is forgotten (never revoked), and the copy enrols as itself. This also holds
|
||
on the same server, where production's token would otherwise work.
|
||
- "Disconnect" on a copy revokes nothing of production's.
|
||
- A staging copy that must not send at all: `iapl({ mail: { relay: false } })` there, or SMTP to a catcher.
|
||
- Not covered: a copy that keeps production's `serverURL` is the same site to the plugin.
|
||
|
||
### The state block in the panel
|
||
|
||
Site integrations → E-mail sending starts with "How e-mails are sent" (component `MailRelayStatus` from `/admin`,
|
||
rendered by the tab's status banner — **no import-map entry of its own, so nothing to regenerate**): 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; **refused** calls are rate-limited (10 a minute per address, `mail.relay.confirmRateLimit`) — a call that carries the nonce is never turned away by the limit, so junk from the same address cannot keep the site from enrolling |
|
||
|
||
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; or a token issued by hand stopped working (new server address, token no longer valid) | "When the site cannot be confirmed" below; hand-issued: ask Intecion for the address to be added or for a new token |
|
||
| `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 |
|
||
| `totalTimeoutMs` | `10000`; `30000` with files | everything one message may take — enrolment, attempts and waits together. Somebody waits for the request that sends the mail; after it the message is reported ("not confirmed" when an attempt was cut off). A number, or `{ plain, files }` |
|
||
| `timeoutMs` | `30000` | one attempt of a send; never more than what is left of `totalTimeoutMs` |
|
||
| `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()`.
|
||
**Without that route in the config the site does not ask to be enrolled at all** (`mailAdapter()` without `iapl()`,
|
||
or `mailAdapter({ relay: {} })` beside `mail: { relay: false }`): the send reports `relay-refused` and says which
|
||
route is missing. A token from `relay.token` needs no route.
|
||
- **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
|
||
|
||
`nodemailer` (`^10.2.1`) is already in the plugin's `dependencies` — the project does not need to
|
||
install it (nodemailer 10 ships its own types, so `@types/nodemailer` is not needed either). Graph is plain
|
||
`fetch`, no extra packages.
|
||
|
||
- **Node.js 20 or later** — nodemailer 10 requires it (the Coolify images run Node 22).
|
||
- **Why `^10.2.1`:** every nodemailer up to 10.1.3 has open advisories (address parser ReDoS, recipient-domain
|
||
bypass, `raw`/`resolveContent` file access). Do not pin an older nodemailer in the project.
|
||
- **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.
|
||
|
||
## The sendEmail helper (server)
|
||
|
||
```ts
|
||
import { sendEmail } from '@intecion/ipal-kit/server'
|
||
|
||
const result = await sendEmail({
|
||
payload,
|
||
to: '[email protected]',
|
||
subject: 'Nowa wiadomość',
|
||
html: '<h1>Cześć</h1><p>Treść…</p>', // finished HTML (your design)
|
||
// text: 'plain version', from: '...', replyTo: '...'
|
||
})
|
||
|
||
if (result.sent) {
|
||
// result.messageId
|
||
} else {
|
||
// result.error — e.g. "SMTP is not configured..."
|
||
}
|
||
```
|
||
|
||
- Always the SMTP from the panel (not Graph, not `mailAdapter`); without `smtpHost`/`smtpUser`/`smtpPassword`
|
||
→ `{ sent: false, error: 'SMTP is not configured in Site integrations.' }`.
|
||
- `from` overrides the address (the name still comes from `smtpFromName`); without `from` and without
|
||
`smtpFromAddress` → `{ sent: false, error: 'No from-address configured.' }`.
|
||
- **The HTML is your argument** — the plugin has no templates, it sends what you pass.
|
||
You build the mail's look in the frontend.
|
||
- Returns `{ sent: true, messageId }` or `{ sent: false, error }` — it does not
|
||
throw and does not leak SMTP details to the client (SMTP error → generic
|
||
`'Failed to send email.'`, details in the log).
|
||
- Port 465 → implicit TLS, others → STARTTLS.
|
||
- `server-only` — the SMTP password never ends up in the browser bundle.
|
||
|
||
## Payload system mail
|
||
|
||
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)
|
||
|
||
Sensitive fields in Site integrations (`smtpPassword`, `turnstileSecretKey`) are
|
||
masked in the UI — they show `••••` instead of plaintext, with
|
||
a Reveal/Hide button. This is UI masking, NOT hashing or encryption:
|
||
the value in the database is plaintext (it must be recoverable for SMTP / Turnstile authentication).
|
||
It protects against shoulder-surfing and showing the panel by accident.
|
||
|
||
Wired through `admin.components.Field: '@intecion/ipal-kit/admin#MaskedField'`.
|
||
Works on any `text` field. After wiring it in a project you may need
|
||
`payload generate:importmap` so the panel recognizes the component.
|
||
|
||
> The main protection of secrets remains `read: isAdmin` on the SiteIntegrations global
|
||
> (anonymous users do not get it). Masking is an extra layer (shoulder-surfing), not
|
||
> database protection — if the DB leaks, the secrets are readable.
|
||
|
||
|
||
## Microsoft Graph (Exchange / M365) — deprecated
|
||
|
||
> **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 IWSN".
|
||
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)
|
||
|
||
**Secrets in `.env`** (agency-level — your Exchange, the client does not see it):
|
||
|
||
```bash
|
||
GRAPH_TENANT_ID=...
|
||
GRAPH_CLIENT_ID=...
|
||
GRAPH_CLIENT_SECRET=...
|
||
GRAPH_SENDER=[email protected] # one mailbox for all projects
|
||
```
|
||
|
||
**From the panel** (per project) it reads the existing SMTP fields — no new fields:
|
||
- `smtpFromName` → sender display name; **the From address is always `GRAPH_SENDER`**
|
||
(no name → the `from` field is omitted, Graph uses the mailbox's default name),
|
||
- `smtpFromAddress` → **Reply-To** (unless the message has its own `replyTo`).
|
||
|
||
Options `graphAdapter({ fallbackFromAddress, fallbackFromName, largeAttachments, cleanupDelaysMs })` —
|
||
the first two are placeholders Payload requires at startup; the other two are for attachments ("Attachments" below).
|
||
`fetchImpl` is for tests.
|
||
|
||
Low-level (when the transport should be fixed in the config):
|
||
|
||
```ts
|
||
import { panelSmtpAdapter, graphAdapter } from '@intecion/ipal-kit'
|
||
email: process.env.GRAPH_CLIENT_ID ? graphAdapter() : panelSmtpAdapter()
|
||
```
|
||
|
||
### Azure / Exchange setup (one-time, your side, OUTSIDE the code)
|
||
|
||
1. **App registration** in Azure AD → `tenantId`, `clientId`
|
||
2. **Client secret** → `clientSecret`
|
||
3. **API Permissions** → Microsoft Graph → **Application** → `Mail.Send` →
|
||
**Grant admin consent** (without it: `Insufficient privileges`)
|
||
4. **Exchange Admin Center** → mailbox `[email protected]` → Mailbox
|
||
Delegation → the app gets **"Send As"** (without it: `ErrorAccessDenied`)
|
||
|
||
### Technical details
|
||
|
||
- Auth: client credentials flow, scope `https://graph.microsoft.com/.default`
|
||
(NOT `Mail.Send` — Azure rejects it, AADSTS1002012)
|
||
- Sending: `POST /users/{sender}/sendMail` (NOT `/me` — app-only has no "me")
|
||
- Success: HTTP 202 (empty body)
|
||
- Plain REST (fetch), zero Microsoft libraries, zero new dependencies
|
||
|
||
### From vs Send-As
|
||
|
||
The adapter does **not** send from the address in the panel — From is always the `GRAPH_SENDER` address
|
||
(only the display name changes), and `smtpFromAddress` from the panel goes into
|
||
Reply-To. So Exchange does not need Send-As on other domains; replies go
|
||
to the client's address. The OAuth token is cached in the process until a minute before it expires,
|
||
`saveToSentItems: false`.
|
||
|
||
## Attachments
|
||
|
||
`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, and
|
||
such a message fails whole (`relay-error`). **Inline images** (`cid:` attachments) are carried as ordinary files:
|
||
the picture shows as an attachment and as a broken image in the text — link images by URL instead. Only the first
|
||
`replyTo` address is used; free headers (`List-Unsubscribe` among them) are dropped.
|
||
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**,
|
||
and it counts the encoded message: a server limit of 10 MB carries about a 7 MB file, 25 MB about 18 MB, 35 MB
|
||
about 25 MB. The recipient's mailbox has its own limit too. Do not trust a table — **measure**: Site integrations →
|
||
E-mail sending → **Test e-mail** with **Attach a 10 MB test file** ticked (endpoint: `POST /api/ipal/test-email`,
|
||
body `{ to, attachmentMB }`, 1–25). A server that refuses the size answers at send time (`552 …`); the adapter
|
||
reports `{ sent: false, detail }`.
|
||
|
||
### Microsoft Graph
|
||
|
||
| Attachments in one message | How it is sent | Permission | Left in the mailbox |
|
||
|---|---|---|---|
|
||
| under 3,000,000 bytes in total | inside the one `sendMail` call | `Mail.Send` | nothing (`saveToSentItems: false`) |
|
||
| more | a **draft** is created in the sender mailbox, files are added (an **upload session** for files of 3 MiB and more, in pieces of 3.2 MB), the draft is sent | `Mail.ReadWrite` | a copy passes through Drafts and Sent Items; **the plugin deletes it** |
|
||
|
||
The large path, step by step, and what happens when it fails:
|
||
|
||
- Any failure before the send (creating the draft, an upload, the send call) → the draft is deleted at once and the
|
||
result is `{ sent: false, code: 'graph-error' }`. Nothing with the file stays in the mailbox.
|
||
- After a successful send the copy in Sent Items is deleted: the plugin looks at the message after 2 s, 5 s, 15 s and
|
||
60 s (`cleanupDelaysMs`), and deletes it once it has left Drafts — never earlier, so the send is not cancelled.
|
||
It uses `permanentDelete`, and a plain delete when that is not available. If the copy could not be removed, the
|
||
server log says `delete it by hand (it holds a form file)`.
|
||
- The app's token lacks `Mail.ReadWrite` → nothing is created; the result is `code: 'graph-permission'` and the
|
||
log names the permission. With `mailAdapter()`:
|
||
- the panel has SMTP settings → the message goes **over SMTP** instead;
|
||
- no SMTP settings → the send fails, and the form's file limit drops to about 2.8 MB so visitors are not offered
|
||
more than can be sent; the panel shows "Microsoft Graph cannot send files of 3 MB and more here…".
|
||
- **Turn it off:** `mailAdapter({ graph: { largeAttachments: false } })` (or `graphAdapter({ largeAttachments: false })`)
|
||
— Graph keeps to small attachments; larger ones go over SMTP when the panel has SMTP settings, else the limit
|
||
is about 2.8 MB.
|
||
- `mailAttachmentLimit(payload)` (root) → the ceiling in bytes the current transport can carry, or `null`.
|
||
|
||
#### Azure / Exchange steps for large attachments (one-time, outside the code)
|
||
|
||
1. **Azure portal → App registrations → the app → API permissions → Add → Microsoft Graph → Application
|
||
permissions → `Mail.ReadWrite` → Grant admin consent.** Keep `Mail.Send`. `Mail.Read` is not used by the
|
||
plugin — remove it if nothing else needs it.
|
||
2. **Limit the app to the forms mailbox.** Application permissions cover *every* mailbox of the tenant, and the
|
||
app's secret sits in the environment of every project. In Exchange Online PowerShell:
|
||
```powershell
|
||
# a mail-enabled security group that holds only the sender mailbox
|
||
New-DistributionGroup -Name "ipal-forms-mailbox" -Type Security -Members [email protected]
|
||
New-ApplicationAccessPolicy -AppId <GRAPH_CLIENT_ID> -PolicyScopeGroupId ipal-forms-mailbox `
|
||
-AccessRight RestrictAccess -Description "IAPL: only the forms mailbox"
|
||
Test-ApplicationAccessPolicy -AppId <GRAPH_CLIENT_ID> -Identity forms@intecion.pl # AccessCheckResult: Granted
|
||
Test-ApplicationAccessPolicy -AppId <GRAPH_CLIENT_ID> -Identity someone.else@intecion.pl # AccessCheckResult: Denied
|
||
```
|
||
A new policy can take up to an hour to apply. (Microsoft is moving this to "RBAC for Applications" in
|
||
Exchange Online; a management scope limited to the same mailbox does the same job.)
|
||
3. Nothing changes in the project: the same four `GRAPH_*` variables.
|
||
|
||
**Verify on the real tenant** (the plugin's tests run against a mocked Graph — no test touched a real mailbox):
|
||
|
||
- [ ] Test e-mail with the 10 MB file, transport = Microsoft Graph → arrives with the file intact.
|
||
- [ ] After a minute, **Drafts and Sent Items of the sender mailbox do not contain the message** (also check
|
||
Deleted Items and Recoverable Items — whether `permanentDelete` is honoured on your tenant).
|
||
- [ ] `GRAPH_SENDER` is a **shared mailbox**: Microsoft lists a known issue with upload sessions on shared
|
||
mailboxes. If the test fails with an access or "item not found" error, use `largeAttachments: false`
|
||
(large files then go over SMTP) and report it.
|
||
- [ ] With the access policy in place, the send still works, and `Test-ApplicationAccessPolicy` denies other mailboxes.
|
||
- [ ] A file of 2.9–3.1 MB (both sides of the switch) arrives.
|
||
- [ ] Server log after a send: no `delete it by hand`.
|
||
|
||
## Test send — button in the panel
|
||
|
||
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 IWSN,
|
||
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 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.
|
||
|
||
> 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
|
||
|
||
`mailAdapter()` stores the send result in Site integrations (at most once per 10 min
|
||
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: Invalid login: 535 …`, `Microsoft Graph: Graph sendMail failed (403).`, or the text of a mail service
|
||
code from "Status codes") and the time.
|
||
|
||
`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 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 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 — `payload.sendEmail` (through the wired adapter, marked with `withMailKind` when it is not
|
||
`system`) or `sendEmail` (always SMTP).
|