Co-Authored-By: Claude Fable 5.2 <[email protected]>
330 lines
18 KiB
Markdown
330 lines
18 KiB
Markdown
# email
|
||
|
||
Sending mail with two transports to choose from: **SMTP from the panel**
|
||
(`panelSmtpAdapter`, universal) or **Microsoft Graph** (`graphAdapter`,
|
||
through Exchange/M365). Both implement the same `PayloadEmailAdapter` interface,
|
||
so `payload.sendEmail` and form mail work whatever the choice.
|
||
The project wires the adapter in `buildConfig({ email })` (the recommended dispatcher is `mailAdapter()`),
|
||
and the editor picks the transport in the panel. A separate `sendEmail` helper (from `/server`) sends
|
||
**always through the SMTP** from the panel, bypassing the adapter.
|
||
|
||
## 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.
|
||
|
||
## Config
|
||
|
||
No plugin options — SMTP (`smtpHost`, `smtpPort` (default 587), `smtpUser`,
|
||
`smtpPassword`, `smtpFromAddress`, `smtpFromName`) and `emailTransport` live in
|
||
SiteIntegrations (E-mail sending tab). The editor configures them in the panel.
|
||
|
||
- **The password is write-only and stays with its server**: the panel shows "A value is set"; changing the
|
||
server, port or user name asks for the password again
|
||
([security.md](./security.md) "Stored secrets"). The plugin does **not** set
|
||
`config.email` — you wire the adapter yourself (below).
|
||
|
||
## Front — sendEmail (server)
|
||
|
||
```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.
|
||
|
||
## Note: Payload system mail
|
||
|
||
Password reset / email verification go through Payload's built-in mechanism
|
||
(`config.email`), which the plugin does **not** set by itself. Wire
|
||
`mailAdapter()` / `panelSmtpAdapter()` in `buildConfig({ email })` (below) — then
|
||
this mail also goes through the mailbox from the panel, with no SMTP in env.
|
||
|
||
## Adapter — SMTP from the panel for all of Payload
|
||
|
||
`sendEmail` sends with its own transport. Separately, the plugin provides an adapter that
|
||
connects the same mailbox to `payload.sendEmail`:
|
||
|
||
`mailAdapter()` is recommended (below, "Wiring — choosing the transport") — it contains this
|
||
adapter and adds Graph. SMTP only:
|
||
|
||
```ts
|
||
// payload.config.ts
|
||
import { panelSmtpAdapter } from '@intecion/ipal-kit'
|
||
|
||
export default buildConfig({
|
||
email: panelSmtpAdapter(),
|
||
// panelSmtpAdapter({ fallbackFromAddress, fallbackFromName }) — used only
|
||
// before the panel is filled in (Payload needs the address synchronously at
|
||
// startup, before the global can be read)
|
||
})
|
||
```
|
||
|
||
Options: `fallbackFromAddress` (`'noreply@localhost'`), `fallbackFromName` (`'Website'`).
|
||
The address and name from the panel always win over the message's `from`. CR/LF characters are
|
||
stripped from the subject (protection against header injection through form-builder `{{field}}`).
|
||
Missing SMTP config or a send error → the adapter **does not throw**, it returns
|
||
`{ sent: false, error }` and logs.
|
||
|
||
Once wired, everything in Payload that sends mail goes through the SMTP from Site
|
||
Integrations — including the built-in form-builder mail (Forms → Emails), password
|
||
reset and account verification mail. The adapter reads the config on every
|
||
send, so changing the mailbox in the panel works without a restart.
|
||
|
||
Without an adapter Payload uses a mock that only logs to the console — form-builder
|
||
mail will not go out.
|
||
|
||
## 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.
|
||
|
||
|
||
## Adapter — Microsoft Graph (Exchange / M365)
|
||
|
||
Alternative to SMTP: 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.
|
||
|
||
### Wiring — choosing the transport (recommended: `mailAdapter`)
|
||
|
||
```ts
|
||
// payload.config.ts
|
||
import { mailAdapter } from '@intecion/ipal-kit'
|
||
|
||
email: mailAdapter(), // SMTP or Graph — chosen in the panel, on EVERY send
|
||
```
|
||
|
||
`mailAdapter` is a dispatcher: it reads `emailTransport` from Site integrations on every
|
||
send (no value → `'smtp'`), so the switch in the panel works without a restart.
|
||
Graph only when all 4 `GRAPH_*` variables are in env — otherwise a clear log and
|
||
fallback to SMTP (mail is not lost silently).
|
||
|
||
Options: `fallbackFromAddress`, `fallbackFromName` (for both delegates), `smtp`
|
||
(`PanelSmtpAdapterArgs`), `graph` (`GraphAdapterArgs`).
|
||
|
||
Low-level (when the transport should be fixed in the config):
|
||
|
||
```ts
|
||
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 both transports
|
||
(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.
|
||
|
||
### 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 "ipal-kit: 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`.
|
||
|
||
## Transport switch — mailAdapter
|
||
|
||
`mailAdapter()` is a dispatcher: one adapter wired in the config, it picks the transport
|
||
(SMTP/Graph) on EVERY send by reading the setting from the panel. That is why
|
||
the switch works in the panel (Payload builds the adapter once at startup, so you cannot
|
||
swap separate adapters at runtime — the dispatcher delegates internally).
|
||
|
||
```ts
|
||
// payload.config.ts — ONE adapter, the choice happens inside
|
||
import { mailAdapter } from '@intecion/ipal-kit'
|
||
email: mailAdapter()
|
||
```
|
||
|
||
Panel → Site integrations → E-mail sending → **Sending method** (SMTP / Microsoft Graph).
|
||
The dispatcher reads this choice per send. Guard: if Graph is selected but the
|
||
secrets are missing in .env → log + fallback to SMTP (no silent failure).
|
||
|
||
## Test send — button in the panel
|
||
|
||
The E-mail sending tab has a **Send test** button: enter an address, click, and a test
|
||
mail goes out through the CURRENT transport (`payload.sendEmail`). It shows the result (✓/✗ with the error).
|
||
Tick **Attach a 10 MB test file** to check that the mail server takes a file of that size ("Attachments" above). Endpoint
|
||
`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).
|
||
Save your changes before the test — the endpoint reads from the database, not from the field on screen.
|
||
|
||
> The button shows only the adapter's short error (e.g. `Graph sendMail failed (403).`,
|
||
> `Failed to send email.`, `SMTP is not configured…`). The full Graph / SMTP response
|
||
> (`ErrorSendAsDenied`, `Insufficient privileges`, `535 …`) is in the **server logs**;
|
||
> for SMTP the detail also goes to the status banner (below).
|
||
|
||
## 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: SMTP is not configured…`, `SMTP: Invalid login: 535 …`,
|
||
`Microsoft Graph: Graph sendMail failed (403).`) and the time.
|
||
|
||
Only `mailAdapter` stores the status — `panelSmtpAdapter` / `graphAdapter` alone and
|
||
the `sendEmail` helper do not update it.
|
||
|
||
The form **keeps working** meanwhile — the submission is saved in Form Submissions,
|
||
only the mail did not go out. Graph selected in the panel without `GRAPH_*` in env → warning
|
||
"sent over SMTP". Changing the SMTP / transport fields in the panel clears the status; after the next
|
||
send (e.g. **Send test**) the current one appears.
|
||
|
||
## Turn off, override, extend
|
||
|
||
- **Turn off:** the plugin does not set `config.email` itself — without `email:` in `buildConfig` Payload uses
|
||
its mock (mail only in the console). The SMTP fields in Site integrations and the endpoint
|
||
`POST /api/ipal/test-email` are currently always added.
|
||
- **Choosing the transport:** `mailAdapter()` (the panel decides) or a fixed `panelSmtpAdapter()` /
|
||
`graphAdapter()`; any other Payload adapter (e.g. `@payloadcms/email-nodemailer`) also works —
|
||
then you skip the panel SMTP and the send status.
|
||
- **Override:** `fallbackFromAddress` / `fallbackFromName`, in `mailAdapter` separately `smtp` and `graph`
|
||
(`graph.largeAttachments: false` keeps Graph to attachments under 3 MB — "Attachments").
|
||
- **Extend:** form mail content is modified by `forms.beforeEmail` (see [forms.md](./forms.md));
|
||
your own mail — `sendEmail` (SMTP) or `payload.sendEmail` (through the wired adapter).
|