Co-Authored-By: Claude Fable 5.2 <[email protected]>
841 lines
60 KiB
Markdown
841 lines
60 KiB
Markdown
# email
|
||
|
||
Mail works with **no setup**: a new site 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 — "Sending method": **IWSN (built-in)** | `[email protected]`; replies go to the panel's "Sender address" |
|
||
| **SMTP from the panel** (`panelSmtpAdapter`) | "Sending method": **Own SMTP server** — on the client's request: its own mail server, its own sender address | the panel's "Sender address" |
|
||
| **Microsoft Graph** (`graphAdapter`) | "Sending method": **Microsoft Graph (deprecated)** — **deprecated since 1.17.0, removed in 2.0**; needs the `GRAPH_*` variables on the server | `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 the admin's choice in the panel.
|
||
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
|
||
|
||
**The one an admin chose** in Site integrations → E-mail sending → **"Sending method"** (since 1.17.1): "IWSN
|
||
(built-in)", "Own SMTP server" or "Microsoft Graph (deprecated)". What is chosen is what is used, and it is shown:
|
||
the state block names it, the test e-mail names it, and only the fields of the chosen method are on the page (the
|
||
SMTP server, port, user name and password under "Own SMTP server"; the service's state block under "IWSN").
|
||
|
||
- **No silent switch.** Which fields happen to be filled in, or which variables the server has, no longer picks
|
||
the method. "IWSN" chosen with an SMTP server filled in sends through the service; "Own SMTP server" chosen
|
||
never contacts the service.
|
||
- **A chosen method that cannot be used fails loudly, and nothing is sent another way:**
|
||
|
||
| Chosen | What is wrong | A send | Where it shows |
|
||
|---|---|---|---|
|
||
| Own SMTP server | server, user name or password missing | `{ sent: false, code: 'not-configured' }` | state block: "Your SMTP server is chosen, but its settings are incomplete…"; status `smtp-incomplete`; doctor `mail-method` (error) |
|
||
| Microsoft Graph | the `GRAPH_*` variables are not on this server | `{ sent: false, code: 'graph-not-set-up' }` — SMTP is **not** tried | state block: "Microsoft Graph is chosen, but it is not set up on this server…"; status `graph-not-set-up`; doctor `mail-method` (error) |
|
||
| IWSN | the service cannot call the site back, the site is disconnected, waits for approval, is a held copy … | `relay-refused`, `relay-pending`, … (below) | the service's state block; doctor `mail-relay-state` |
|
||
|
||
A form submission is stored whatever happens to its e-mail, as before.
|
||
- One exception that was always there: with **Microsoft Graph** chosen, a file too large for Graph goes over the
|
||
panel's SMTP server when one is filled in ("Attachments" below).
|
||
- `mail: { relay: false }` takes the option "IWSN" away; a choice of it stored earlier then counts as no choice.
|
||
|
||
**Where the choice is stored.** In Payload's key-value store (`payload-kv`, key `MAIL_METHOD_KV_KEY`), not in a
|
||
column: the panel's field `emailMethod` is **virtual**. So **no SQL schema changes and no migration exists** —
|
||
a third value in the stored select `emailTransport` (`smtp` / `graph` since 1.6) would have changed the Postgres
|
||
enum, and could still not tell "SMTP was chosen" from the `smtp` every site has stored since before there was a
|
||
choice. `emailTransport` stays, hidden in the panel, and follows the choice where it can say it (`graph`, else
|
||
`smtp`). From code: `getMailMethod(payload)` (`'relay' | 'smtp' | 'graph' | null`), `setMailMethod(payload, method)`
|
||
(a seed or a deploy script; `null` = nobody has chosen), `payload.updateGlobal({ slug: 'site-integrations', data: {
|
||
emailMethod: 'smtp' } })`, `resolveMailMethod(settings, { chosen, graphEnv, relay })` →
|
||
`{ method, explicit, problem? }` (types `MailMethod`, `ResolvedMailMethod`, `MailMethodProblem`; `MAIL_METHODS`,
|
||
`isMailMethod`).
|
||
|
||
**Until somebody chooses — a site upgraded from 1.17.0 or older, and a new site.** Nothing is written on upgrade.
|
||
The method follows the order of 1.17.0, the field shows it **as selected**, and mail keeps leaving the way it did
|
||
(`resolveMailTransport(settings, { graphEnv, relay })` returns `'graph' | 'smtp' | 'relay' | 'none'`, type `MailTransport`):
|
||
|
||
1. `emailTransport` is `graph` **and** the four `GRAPH_*` variables are set → **Graph** (deprecated).
|
||
2. The panel has an SMTP server (server, user name and password) → **SMTP**.
|
||
3. The four `GRAPH_*` variables are set → **Graph** (deprecated).
|
||
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' }`.
|
||
|
||
| The site before the upgrade | "Sending method" shows | Mail |
|
||
|---|---|---|
|
||
| 1.17.0, no SMTP server (sends through the service) | IWSN (built-in) | as before |
|
||
| SMTP server filled in (1.16.x or 1.17.0) | Own SMTP server | as before |
|
||
| `GRAPH_*` on the server (with "Microsoft Graph" stored, or with no SMTP server) | Microsoft Graph (deprecated) | as before, with the deprecation notice |
|
||
| half an SMTP set-up, no `GRAPH_*` | IWSN (built-in), with the hint "The SMTP settings below are incomplete" | through the service, as in 1.17.0 |
|
||
| a new site | IWSN (built-in) | through the service |
|
||
|
||
**The first save of Site integrations stores what the form shows** (the form always sends the field), and from
|
||
then on the method is fixed. The state block says "Nobody has chosen the sending method yet, so the site picked
|
||
this one. Save this page to keep it." until then, and the doctor's deep run notes it (`mail-method`, info). A script
|
||
of before 1.17.1 that writes `emailTransport` alone still means what it meant: it puts the site back on the order
|
||
above (write `emailMethod` to choose).
|
||
|
||
- 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.
|
||
|
||
## 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 site that passes the call-back is active at once.** Waiting for approval is the exception: the service
|
||
holds a new site back when many new sites appear at once (more than a few a day from one address or domain, or
|
||
more than its daily number in all), or when Intecion has set it to approve by hand. Mail is then not sent until
|
||
Intecion approves the site; the same token works afterwards, and the panel says so.
|
||
|
||
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"). It answers from what is stored — never by asking the service while a page
|
||
is read — and is renewed after a send, once an hour; until the site has enrolled and sent once 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
|
||
one entry per host under `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, and is stored under that host** (key
|
||
`iapl:mail-relay:site:<host>`). A site reads and writes its own entry only; another host's entry in the same
|
||
database — production's in a copy, the old domain's after a move, the live site's when a developer's process
|
||
reads the live database — is neither used nor touched. **A read never deletes or changes anything.**
|
||
- 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, on every way in.** A token stored by a script is checked with the service
|
||
before its first use (`/v1/status` names the host), the panel's access-key field asks before it stores anything,
|
||
and every request names the site, so the service refuses a foreign token from `relay.token` too
|
||
(`host-mismatch`): another site's token is not saved, not used and not revoked.
|
||
- **A token issued by hand** — only for a site the service **cannot call back**: behind a firewall or basic auth, on
|
||
a private network, or one that cannot serve the confirm route. Every other site enrols by itself and needs none.
|
||
Intecion issues the token for the site's host; **a developer sets it**, one of three ways:
|
||
|
||
```ts
|
||
// 1. once, from a script (recommended): pnpm payload run scripts/set-mail-token.ts
|
||
// stored in payload-kv like an enrolled token; the plugin rotates it every 90 days
|
||
import config from '@payload-config'
|
||
import { setRelayToken } from '@intecion/ipal-kit'
|
||
import { getPayload } from 'payload'
|
||
|
||
const payload = await getPayload({ config })
|
||
await setRelayToken(payload, process.env.MAIL_TOKEN!) // pass it in the environment of this one run; never commit it
|
||
process.exit(0)
|
||
```
|
||
|
||
```ts
|
||
// 2. from the deployment's own secret, on every start: nothing is stored, the site never enrols,
|
||
// and replacing the token before it runs out is the project's job
|
||
iapl({ mail: { relay: { enrol: false, token: () => process.env.MY_MAIL_TOKEN } } })
|
||
```
|
||
|
||
3. In the panel, when the project switches the field on: `mail: { relay: { accessKeyField: true } }` adds
|
||
"Enter an access key" to the state block for admins. **Off by default** — without it the block has no such
|
||
field and its route takes no token (`403`).
|
||
**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, copies and several hosts
|
||
|
||
- **A site that passes the call-back is active at once** and can send. A staging site on its own domain is its own
|
||
site to the service: its own enrolment, token and limits.
|
||
- **Launch and a domain move need nobody.** A site is usually built and enrolled on a development address
|
||
(`client.dev.agency.example`) and then served on its real domain, with the same data. The real domain finds the
|
||
development address's connection in its database, treats it as its own past, enrols by itself on its first
|
||
e-mail and sends. The same after a move to another domain. No button, no option.
|
||
- **A non-public copy does not send by itself.** A copy of production's data holds real customers' addresses —
|
||
form submissions, accounts — and would mail real people as soon as a form or a password reset ran. The plugin
|
||
tells the two apart by **direction**: a site that is **not public** — its host matches a development pattern, or
|
||
`IAPL_NOINDEX=1` is set; either is enough (see "Which sites are non-public" below)
|
||
— and whose database holds the connection of **another host** neither enrols nor sends: sends report
|
||
`relay-refused` (cause `client-other-host`), the state block says "The data comes from another site (…), so this
|
||
copy does not send e-mails by itself", the doctor reports it (`mail-relay-state`), and no call leaves the server.
|
||
This also holds when the copy has a token of its own: production's database copied **back** onto the development
|
||
address brings that address's old connection with it, and still mails nobody.
|
||
- **An admin who wants the copy to send** presses **Connect again**, once. That is stored in the copy's database;
|
||
the next fresh copy of production replaces it and waits again.
|
||
- **A site before launch is not affected:** with no other host in its database it enrols by itself on its first
|
||
e-mail, on a development address too — clients test their forms there.
|
||
|
||
**Which sites are non-public.** No environment variable is needed:
|
||
|
||
- **By host, from code.** `iapl({ developmentHosts })` is a list of host patterns (`*` = any characters; the whole
|
||
host must match). Its default is `DEFAULT_DEVELOPMENT_HOSTS` = **`['*.dev.netscale.pl']`**. That name is in the
|
||
plugin on purpose: it is Intecion's own development domain, every site of the team is built at
|
||
`<name>.dev.netscale.pl` before it moves to its real domain, and nothing in those sites' environments marks them
|
||
as development copies — with the pattern built in they are protected without an edit. It is a default like any
|
||
other: **replace it** with your own patterns (`developmentHosts: ['*.preview.agency.example', 'staging.client.pl']`),
|
||
or pass **`[]`** so that no host is a development address. `mail: { relay: { developmentHosts } }` overrides the
|
||
list for the mail service alone.
|
||
- A malformed list stops the start (`assertDevelopmentHosts`): the value must be an array of non-empty host patterns — a single string, `null`, a number, an empty string, a scheme or a path are refused, and so is a pattern made of `*` alone (it would make the public site a development address). Patterns are compared as hosts are written on the wire: lowercase, punycode (a pattern may be written in Unicode), a trailing dot ignored, the port ignored.
|
||
- **By the variable.** `IAPL_NOINDEX=1` marks any other staging, preview or test copy.
|
||
- The list is about mail only: it does **not** make a development host noindex. Keeping development addresses out of search engines stays the hosting's business (Coolify) or `IAPL_NOINDEX=1`.
|
||
- The panel state (`nonPublicBy`, `nonPublicPattern`), `siteNonPublicSignal(payload)` and the doctor
|
||
(`mail-non-public`) say which of the two applies.
|
||
|
||
| The site | Public? | Its database holds | By itself |
|
||
|---|---|---|---|
|
||
| on its development address, before launch | no | nothing, or only its own connection | enrols and sends |
|
||
| on the real domain, launch day (the development site may still run on its own database) | yes | the development address's connection | **enrols and sends — no click** |
|
||
| after a domain move; a second domain | yes | the old domain's connection | enrols and sends |
|
||
| `www.` and the bare domain | either | each other's | one site: both send, each with its own entry |
|
||
| staging / test copy of production on a development host, or with `IAPL_NOINDEX=1` | no | production's connection | **sends nothing** until "Connect again" |
|
||
| production's database copied back onto the development address | no | production's and its own old one | **sends nothing** until "Connect again" |
|
||
| a developer's `localhost` on the production database | — | production's | refused before any call (not a public host); reads and writes nothing of production's |
|
||
| a copy on a host **outside** the development patterns, without `IAPL_NOINDEX` | yes | production's | **enrols and sends, to the real addresses in its data** — see below |
|
||
|
||
- **What remains possible — say it to whoever sets up a copy:**
|
||
- A copy on a host that matches no development pattern and has no `IAPL_NOINDEX=1` looks exactly like launch
|
||
day and **sends**. The doctor's deep run reports the only sign there is, as information: "the database also
|
||
holds the mail-service connection of another host, and this site is public" (`mail-relay-state`). A project
|
||
whose copies live elsewhere than `*.dev.netscale.pl` names its own patterns in `developmentHosts`.
|
||
- A project that empties the list (`developmentHosts: []`) has only `IAPL_NOINDEX` left as a mark.
|
||
- A **public** site served on a host that matches a development pattern is treated as a development address:
|
||
it sends its own mail, but after a copy of another site's data it waits for "Connect again". Take the host out
|
||
of the list.
|
||
- A production site that still has `IAPL_NOINDEX=1` after launch counts as non-public: it finds the development
|
||
address's connection and **sends nothing** (and is not indexed either). The state block and the doctor say why;
|
||
removing the variable is the fix ([deployment.md](./deployment.md): "`IAPL_NOINDEX` NOT set in production").
|
||
- A copy that keeps production's `serverURL` is the same site to the plugin (and to the service, if it can be
|
||
called back at that host).
|
||
- After "Connect again" a copy sends until its data is replaced.
|
||
- A development site that keeps running **on the launched database** (not a copy of it) stops sending by itself
|
||
once the real domain has enrolled. The check reads the database at every send, so a dump restored into a running
|
||
development site stops its very next e-mail.
|
||
- **A copy that must never send:** `iapl({ mail: { relay: false } })` there, or SMTP to a catcher. That is the safe
|
||
set-up for staging; the rule above only protects until somebody presses the button.
|
||
- **`otherHosts`** changes the rule: a list (`['client.dev.agency.example']`) names hosts as this site's own — a
|
||
non-public site is not held by them, and the doctor's note about a launched site goes away; `'wait'` is the
|
||
stricter rule — also a public site without a connection of its own waits for "Connect again"; `'enrol'` switches
|
||
the rule off.
|
||
- Production's connection is never used, changed or revoked by a copy — "Disconnect" on a copy included, and on the
|
||
same server too. A developer's process on `localhost` reading the live database changes nothing either.
|
||
|
||
### 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** — and **Enter an access key** only
|
||
with `mail.relay.accessKeyField: true` ("The token" above).
|
||
|
||
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 — only with `accessKeyField: true`, otherwise `403` |
|
||
| `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, but held for approval by Intecion — the rule while the service runs with enrolment "pending" (from its launch until Intecion switches to open enrolment), every new site waits for approval; after that the exception (many new sites at once, or approval by hand) | 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 |
|
||
| `otherHosts` | `'auto'` | a database that holds another host's connection. `'auto'`: a public site enrols by itself (launch, a domain move); a non-public one (`IAPL_NOINDEX=1` or `developmentHosts`) neither enrols nor sends until "Connect again". A list = those hosts are this site's own. `'wait'` = a public site without a connection of its own waits too. `'enrol'` = no rule |
|
||
| `developmentHosts` | the plugin's list: `iapl({ developmentHosts })`, default `['*.dev.netscale.pl']` (`pluginDevelopmentHosts(payload)`) | host patterns (`*` = any characters) of development, staging and preview addresses, for the mail service alone: a site on such a host is non-public for `otherHosts`, like one with `IAPL_NOINDEX=1`, with no environment variable (`siteIsNonPublic`, `siteNonPublicSignal`, `matchDevelopmentHost`, `isDevelopmentHost`). `[]` = none |
|
||
| `enrol` | `'auto'` | `'manual'`: only "Connect again" or `enrolRelay()` enrols. `false`: never (the token comes from `token` or `setRelayToken`) |
|
||
| `accessKeyField` | `false` | `true` shows "Enter an access key" in the state block and lets its route store a hand-issued token an admin pastes |
|
||
| `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`) live in Site integrations (E-mail sending tab); server, port, user name and password are shown
|
||
while "Sending method" is "Own SMTP server". Choose that method, fill them in and save: the site sends through the
|
||
client's server (a site nobody has chosen a method for yet does so as soon as the three are filled in).
|
||
|
||
- **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.
|
||
- **Time-outs** (since 1.17.0): 10 s to connect, 30 s for the server's greeting, 60 s of silence during the
|
||
dialogue (`SMTP_TIMEOUT_DEFAULTS`; nodemailer's own were 2 min and 10 min). A send inside a database transaction —
|
||
Payload's "forgot password" with `mail: { accountMailAfterCommit: false }` — holds a connection that long
|
||
([deployment.md](./deployment.md) §4.3a; by default that mail goes out after its transaction commits). Change them:
|
||
`mailAdapter({ smtp: { timeouts: { connectionMs, greetingMs, socketMs } } })` or `panelSmtpAdapter({ timeouts })`
|
||
(type `SmtpTimeouts`).
|
||
|
||
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'`), `timeouts`
|
||
(`{ connectionMs: 10000, greetingMs: 30000, socketMs: 60000 }`).
|
||
|
||
## 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"). Payload sends them inside the operation's database transaction; `mailAdapter()`
|
||
sends them right **after** it commits instead (still in the same request; nothing when it is rolled back), so a slow
|
||
mail server holds no database connection — `mail: { accountMailAfterCommit: false }` keeps them inside
|
||
([deployment.md](./deployment.md) §4.3a). The message is matched to its request by the token it carries (and the
|
||
account's address), never by the address alone: a form's mail to the same address goes out as usual. A project's own
|
||
`forgotPassword.generateEmailSubject` / `verify.generateEmailSubject` is kept; an own `generateEmailHTML` must put the
|
||
token in the body (any working reset link does), or that mail is sent inside the transaction as before. An e-mail adapter of your own does the same by calling
|
||
`sendAccountMailAfterCommit(message, () => send(message))` first.
|
||
|
||
## 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. Tell Intecion the host: while the service runs with enrolment "pending" (from its launch until Intecion switches to open enrolment), every new site waits for approval; the panel says so. Under open enrolment the site is active as soon as it enrols.
|
||
3. Site integrations → E-mail sending → "Sending method": choose **IWSN (built-in)** and save. Then remove the four
|
||
`GRAPH_*` variables in Coolify and redeploy.
|
||
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
|
||
`notification@webservices.intecion.net` 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. `forms@intecion.pl`).
|
||
|
||
### 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=...
|
||
[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 `forms@intecion.pl` → 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; many sends failing at once write it once, and while a
|
||
Postgres pool is busy the write goes on in the background — [integrations.md](./integrations.md)). 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` (with
|
||
`smtp.timeouts`) 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).
|