- nodemailer ^8.0.1 -> ^10.2.1 (advisories up to 10.1.3); drop @types/nodemailer, nodemailer 10 ships its own types. Node engines >=20.9.0 (nodemailer 10 needs 20+). - pnpm.overrides (repo only, not passed to projects) for packages in payload 3.90.2's tree: undici and dompurify are exact-pinned upstream; fast-uri, js-yaml, browserslist, source-map-js, fast-copy, baseline-browser-mapping raised to fixed minimums. pnpm audit --prod: 19 high / 35 moderate / 11 low -> 0. - Tests: SMTP over a local SMTP socket with real nodemailer (panelSmtpAdapter, sendEmail, unreachable server status), Microsoft Graph and Graph->SMTP fallback via mailAdapter; real payloadTotp through ipalKit, plus a check that payload-2fa resolves the project's payload. - Docs: email.md, AGENT.md §4 item 12, ipal-setup, ipal-upgrade, README. Co-Authored-By: Claude Opus 5.5 <[email protected]>
12 KiB
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/resolveContentfile access). Do not pin an older nodemailer in the project. - Since nodemailer 9, attachments given as an
href/pathURL 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 plugin does not set
config.email — you wire the adapter yourself (below).
Front — sendEmail (server)
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); withoutsmtpHost/smtpUser/smtpPassword→{ sent: false, error: 'SMTP is not configured in Site integrations.' }. fromoverrides the address (the name still comes fromsmtpFromName); withoutfromand withoutsmtpFromAddress→{ 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:
// 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: isAdminon 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):
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 alwaysGRAPH_SENDER(no name → thefromfield is omitted, Graph uses the mailbox's default name),smtpFromAddress→ Reply-To (unless the message has its ownreplyTo).
Options graphAdapter({ fallbackFromAddress, fallbackFromName }) — only placeholders
Payload requires at startup.
Wiring — choosing the transport (recommended: mailAdapter)
// 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):
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)
- App registration in Azure AD →
tenantId,clientId - Client secret →
clientSecret - API Permissions → Microsoft Graph → Application →
Mail.Send→ Grant admin consent (without it:Insufficient privileges) - 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(NOTMail.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 fetched on every send (no cache),
saveToSentItems: false.
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).
// payload.config.ts — ONE adapter, the choice happens inside
import { mailAdapter } from '@intecion/ipal-kit'
email: mailAdapter()
Panel → Site integrations → SMTP → Email Transport (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). Endpoint
POST /api/ipal/test-email, body { to } (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 → SMTP — 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.emailitself — withoutemail:inbuildConfigPayload uses its mock (mail only in the console). The SMTP fields in Site integrations and the endpointPOST /api/ipal/test-emailare currently always added. - Choosing the transport:
mailAdapter()(the panel decides) or a fixedpanelSmtpAdapter()/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, inmailAdapterseparatelysmtpandgraph. - Extend: form mail content is modified by
forms.beforeEmail(see forms.md); your own mail —sendEmail(SMTP) orpayload.sendEmail(through the wired adapter).