# 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: 'kontakt@klient.pl', subject: 'Nowa wiadomość', html: '
Treść…
', // 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. `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=... GRAPH_SENDER=forms@intecion.pl # 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 `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 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 forms@intecion.pl New-ApplicationAccessPolicy -AppId