Files
ipal-kit/src/modules/email/mailAdapter.ts
T
Radosław SmolińskiandClaude Fable 5.2 ee8ea42956 E-mail: "Sending method" is an explicit choice - IWSN (built-in), Own SMTP server, Microsoft Graph (deprecated)
What is chosen is what is used. The choice is the stored field `emailMethod` of Site integrations (empty until
somebody chooses); `emailTransport` of 1.6 - 1.17.0 stays, hidden.

- no silent switch: a chosen method that cannot be used (SMTP incomplete, Graph without GRAPH_*) fails loudly
  - status smtp-incomplete / graph-not-set-up, state block, doctor mail-method - and nothing is sent another way
- upgrade writes nothing and loses no mail: until somebody chooses, the order of 1.17.0 applies and the field
  shows its result as selected; the first save of the panel's form stores the choice
- only the chosen method's fields are shown; the test e-mail names the method (Graph too)
- mail: { relay: false } does not offer "IWSN" (the stored values stay three: one SQL enum for every project)
- Postgres / SQLite: one migration (a column). Before it runs the plugin's readers read the global without the
  field, mail goes the old way, one loud log line and the doctor say what to do
- getMailMethod, setMailMethod, resolveMailMethod, readMailSettings, mailMethodColumnMissing exported
- tests on SQLite, Postgres and MongoDB, with and without the migration; docs, AGENT.md, skills, changelog

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-26 22:39:03 +01:00

296 lines
16 KiB
TypeScript

import type { PayloadEmailAdapter, SendEmailOptions } from 'payload'
import { type IntegrationStatus, recordIntegrationStatus } from '../integrations/status.js'
import { assertDevelopmentHosts } from '../shared/developmentHosts.js'
import { sendAccountMailAfterCommit } from './accountMailAfterCommit.js'
import { graphAdapter, type GraphAdapterArgs, graphLargeAttachmentSupport } from './graphAdapter.js'
import { attachmentBytes, GRAPH_INLINE_MAX_BYTES, toGraphAttachments } from './graphAttachments.js'
import { isMailMethod, type MailMethod, readMailSettings } from './method.js'
import { panelSmtpAdapter, type PanelSmtpAdapterArgs } from './panelSmtpAdapter.js'
import { relayAttachmentLimit, sendRelayWithPanel } from './relay/adapter.js'
import { pluginMailOptions, type RelayOptions, resolveRelayOptions } from './relay/options.js'
type TransportIntegrations = {
/** 'smtp' | 'graph' — chosen by the editor in SiteIntegrations. */
/** "Sending method" as stored: empty = nobody has chosen. */
emailMethod?: null | string
emailStatus?: IntegrationStatus | null
emailTransport?: 'graph' | 'smtp' | null
smtpFromAddress?: null | string
smtpFromName?: null | string
smtpHost?: null | string
smtpPassword?: null | string
smtpUser?: null | string
}
const smtpConfigured = (s: TransportIntegrations) => Boolean(s.smtpHost && s.smtpUser && s.smtpPassword)
/** Some of server, user name and password are filled in, but not all: the SMTP server cannot be used. */
export const smtpIncomplete = (s: TransportIntegrations) => !smtpConfigured(s) && Boolean(s.smtpHost || s.smtpUser || s.smtpPassword)
let warnedSmtpIncomplete = false
/** Which transport a send takes. `none`: nothing is set up and the relay is switched off. */
export type MailTransport = 'graph' | 'none' | 'relay' | 'smtp'
/**
* The transport in effect for the present settings, decided on every send (no stored value):
* 1. "Sending method" is Microsoft Graph and the GRAPH_* variables are complete → Graph, as before
* (deprecated; removed in 2.0);
* 2. the panel has an SMTP server (server, user name, password) → SMTP — on the client's request;
* 3. the GRAPH_* variables are complete → Graph (deprecated), until they are removed;
* 4. otherwise → the Intecion Notifications Webservice, unless it is switched off (`mail: { relay: false }`);
* 5. otherwise nothing is configured.
* A site with SMTP filled in never contacts the service.
*/
export function resolveMailTransport(settings: TransportIntegrations, state: { graphEnv: boolean; relay: boolean }): MailTransport {
if ((settings.emailTransport ?? 'smtp') === 'graph' && state.graphEnv) {return 'graph'}
if (smtpConfigured(settings)) {return 'smtp'}
if (state.graphEnv) {return 'graph'}
return state.relay ? 'relay' : 'none'
}
/** Why the chosen method cannot be used. The mail is NOT sent another way. */
export type MailMethodProblem = 'graph-not-set-up' | 'smtp-incomplete'
export type ResolvedMailMethod = {
/** An admin chose it ("Sending method" was saved); false = nobody has chosen yet, the order of 1.17.0 decides. */
explicit: boolean
method: MailTransport
/** Set only for an explicit choice that cannot be used; sends fail and say so. */
problem?: MailMethodProblem
}
/**
* The sending method in effect. With a choice (`emailMethod`, as stored): exactly that method — an SMTP choice with
* an incomplete server, or Graph without the `GRAPH_*` variables, is a problem and the mail fails loudly;
* nothing is sent another way. Without a choice: `resolveMailTransport`, the order of 1.17.0.
* A choice of the built-in service counts as no choice when the project switched the service off
* (`mail: { relay: false }` removes the option).
*/
export function resolveMailMethod(settings: TransportIntegrations, state: { chosen: MailMethod | null; graphEnv: boolean; relay: boolean }): ResolvedMailMethod {
const chosen = state.chosen === 'relay' && !state.relay ? null : state.chosen
if (!chosen) {return { explicit: false, method: resolveMailTransport(settings, state) }}
if (chosen === 'smtp') {return { explicit: true, method: 'smtp', ...(smtpConfigured(settings) ? {} : { problem: 'smtp-incomplete' as const }) }}
if (chosen === 'graph') {return { explicit: true, method: 'graph', ...(state.graphEnv ? {} : { problem: 'graph-not-set-up' as const }) }}
return { explicit: true, method: 'relay' }
}
/** Graph result codes that mean "Graph cannot carry an attachment this large" — SMTP may. */
const GRAPH_TOO_LARGE = new Set(['graph-large-off', 'graph-permission'])
/** The one warning a site on Microsoft Graph gets per process (silence: `mail: { graphDeprecationWarning: false }`). */
export const GRAPH_DEPRECATION_NOTICE =
'[iapl] Microsoft Graph as the e-mail transport is deprecated and will be removed in 2.0. Remove the GRAPH_* variables to send through the Intecion Notifications Webservice, or fill in an SMTP server in Site integrations (docs/email.md, "Moving off Microsoft Graph").'
const STATUS_FIELD = 'emailStatus'
/** Error text for the panel: first line, no stack, capped — SMTP errors don't carry the password. */
const describe = (err: unknown) =>
(err instanceof Error ? err.message : String(err)).split('\n')[0].slice(0, 200)
export type MailAdapterArgs = {
fallbackFromAddress?: string
fallbackFromName?: string
/** @deprecated Microsoft Graph is deprecated since 1.17.0 and removed in 2.0 (docs/email.md, "Moving off Microsoft Graph"). */
graph?: GraphAdapterArgs
/**
* The Intecion Notifications Webservice — the transport of a site with no SMTP server in the panel.
* `false` switches it off for this adapter; an object overrides `iapl({ mail: { relay } })`.
*/
relay?: false | RelayOptions
smtp?: PanelSmtpAdapterArgs
}
let warnedGraphDeprecated = false
/** iapl() left its options in the config: it has already warned at start (plugin.ts, onInit). */
const pluginWarnsAtStart = (payload: { config?: { custom?: unknown } }) => Boolean((payload.config?.custom as { iapl?: { mail?: unknown } } | undefined)?.iapl?.mail)
/** For tests. */
export function resetGraphDeprecationWarning(): void {
warnedGraphDeprecated = false
}
/** True when the agency Graph credentials are present in the environment. */
export function graphAvailable(): boolean {
return Boolean(
process.env.GRAPH_TENANT_ID &&
process.env.GRAPH_CLIENT_ID &&
process.env.GRAPH_CLIENT_SECRET &&
process.env.GRAPH_SENDER,
)
}
/**
* Dispatcher email adapter: wired into the config ONCE, but picks the transport
* per send from Site integrations (resolveMailTransport): the panel's SMTP server
* when one is filled in, Microsoft Graph while its variables last (deprecated),
* otherwise the Intecion Notifications Webservice (relay/).
* This is what makes the choice switchable in the panel — Payload builds the
* email adapter at boot and can't swap it at runtime, so instead of choosing
* between two adapters at boot we install one that delegates on every send.
*
* Availability guard: Graph only runs if its agency credentials exist in env
* (this is *our* Exchange). If the panel says 'graph' but env isn't set up,
* we DON'T silently fail — we log clearly and fall back to SMTP, so a client
* flipping the switch without the backing config still gets mail out (over SMTP)
* rather than silent nothing. If neither is usable, the send reports an error.
*
* @example
* // payload.config.ts
* import { mailAdapter } from '@intecion/ipal-kit'
* email: mailAdapter()
*/
export const mailAdapter =
(args: MailAdapterArgs = {}): PayloadEmailAdapter =>
(deps) => {
// a malformed list must stop the start, not be found at the first e-mail of a copy
if (args.relay && args.relay.developmentHosts !== undefined) {assertDevelopmentHosts(args.relay.developmentHosts, 'mailAdapter({ relay: { developmentHosts } })')}
// Build both delegates once; each still resolves its own config per send.
const smtp = panelSmtpAdapter({
fallbackFromAddress: args.fallbackFromAddress,
fallbackFromName: args.fallbackFromName,
...args.smtp,
})(deps)
const graph = graphAdapter({
fallbackFromAddress: args.fallbackFromAddress,
fallbackFromName: args.fallbackFromName,
...args.graph,
})(deps)
const { payload } = deps
/**
* The largest total attachment size (bytes) the current transport can
* carry, or null when the plugin knows no ceiling (the mail server's own
* limit still applies). Read by the forms module, so a File field never
* promises more than can be sent: on Graph without the large-file path and
* without SMTP settings the ceiling is GRAPH_INLINE_MAX_BYTES.
*/
const relayOptions = () => resolveRelayOptions(payload, args.relay)
const methodOf = (settings: TransportIntegrations) => resolveMailMethod(settings, { chosen: isMailMethod(settings.emailMethod) ? settings.emailMethod : null, graphEnv: graphAvailable(), relay: Boolean(relayOptions()) })
const attachmentLimit = async (): Promise<null | number> => {
const settings = await readMailSettings<TransportIntegrations>(payload)
const transport = methodOf(settings).method
// The service says what it carries for this site (10 MB unless Intecion set another number).
if (transport === 'relay') {return relayAttachmentLimit(payload, relayOptions()!).catch(() => null)}
if (transport !== 'graph') {return null}
const support = await graphLargeAttachmentSupport(args.graph)
if (support === 'ok' || support === 'unavailable' || smtpConfigured(settings)) {return null}
return GRAPH_INLINE_MAX_BYTES - 1
}
return {
name: 'ipal-mail-dispatcher',
attachmentLimit,
defaultFromAddress: smtp.defaultFromAddress,
defaultFromName: smtp.defaultFromName,
sendEmail: async (message: SendEmailOptions) => {
// Payload's "forgot password" / "verify your e-mail" inside a transaction: sent right after it commits
// (accountMailAfterCommit.ts), so a slow mail server holds no database connection.
if (sendAccountMailAfterCommit(message, () => send(message))) {return { deferred: true }}
return send(message)
},
}
async function send(message: SendEmailOptions): Promise<unknown> {
const settings = await readMailSettings<TransportIntegrations>(payload)
const choice = settings.emailTransport ?? 'smtp'
const previous = settings[STATUS_FIELD]
const resolved = methodOf(settings)
const chosen = resolved.method
// No SMTP server in the panel and no Graph: the Intecion Notifications Webservice.
if (chosen === 'relay') {
// Half an SMTP set-up was "not configured" before 1.17.0; now the mail leaves another way: say so once.
if (!resolved.explicit && smtpIncomplete(settings) && !warnedSmtpIncomplete) {
warnedSmtpIncomplete = true
payload.logger.warn('[iapl] The SMTP settings in Site integrations are incomplete (server, user name and password are all needed), so e-mails go through the Intecion Notifications Webservice. Complete them to use the SMTP server, or empty them.')
}
return sendRelayWithPanel(payload, relayOptions()!, message, settings)
}
// Graph was chosen, but this server has no GRAPH_* variables: the mail fails, and says so. It does not
// leave another way — what is chosen is what is used.
if (resolved.problem === 'graph-not-set-up') {
const error = 'Microsoft Graph is chosen as the sending method, but it is not set up on this server (the GRAPH_* variables are missing). Nothing was sent.'
await recordIntegrationStatus(payload, STATUS_FIELD, previous, { code: 'graph-not-set-up', message: error, state: 'degraded' })
return { code: 'graph-not-set-up', error, sent: false }
}
const useGraph = chosen === 'graph'
// "Graph" in the panel without its variables is reported only while SMTP carries the mail instead.
const graphFallback = !resolved.explicit && choice === 'graph' && !useGraph
if (graphFallback) {
// Panel asked for Graph but the agency creds aren't configured for
// this project. Fall back to SMTP rather than silently dropping mail.
payload.logger.warn(
'[iapl] Transport set to Graph but GRAPH_* env vars are missing; falling back to SMTP.',
)
}
// A project that uses mailAdapter() without iapl()'s start warning still hears it once.
if (useGraph && !warnedGraphDeprecated && !pluginWarnsAtStart(payload) && pluginMailOptions(payload).graphDeprecationWarning !== false) {
warnedGraphDeprecated = true
payload.logger.warn(GRAPH_DEPRECATION_NOTICE)
}
// A large attachment Graph cannot carry (switched off, or the app lacks
// Mail.ReadWrite) goes over SMTP when the panel has SMTP settings.
const attachments = useGraph ? toGraphAttachments(message) : []
const large = Boolean(attachments?.length) && attachmentBytes(attachments ?? []) >= GRAPH_INLINE_MAX_BYTES
const support = large ? await graphLargeAttachmentSupport(args.graph) : 'ok'
const largeOverSmtp = large && support !== 'ok' && support !== 'unavailable' && smtpConfigured(settings)
const viaGraph = useGraph && !largeOverSmtp
const transport = viaGraph ? 'Microsoft Graph' : 'SMTP'
// (SMTP was chosen and its settings are incomplete: its own code, so the panel can say what to fill in)
const code = viaGraph ? 'graph-error' : resolved.problem === 'smtp-incomplete' ? 'smtp-incomplete' : 'smtp-error'
let result: unknown
try {
result = await (viaGraph ? graph : smtp).sendEmail(message)
// Graph found out only while sending (a token it could not read): one try over SMTP. Graph sent nothing.
const refused = result as { code?: string; sent?: boolean } | null
if (viaGraph && refused?.sent === false && GRAPH_TOO_LARGE.has(refused.code ?? '') && smtpConfigured(settings)) {
result = await smtp.sendEmail(message)
}
} catch (err) {
await recordIntegrationStatus(payload, STATUS_FIELD, previous, {
code,
message: `${transport}: ${describe(err)}`,
state: 'degraded',
})
throw err // callers (form-builder, Send test) still see the failure
}
// The delegates report failure as { sent: false, error, detail? } instead
// of throwing (a broken mailbox must not crash a form submission).
const failed = result as { code?: string; detail?: string; error?: string; sent?: boolean } | null
if (failed && typeof failed === 'object' && failed.sent === false) {
await recordIntegrationStatus(payload, STATUS_FIELD, previous, {
code: GRAPH_TOO_LARGE.has(failed.code ?? '') ? 'graph-large-files' : code,
message: `${transport}: ${describe(failed.detail ?? failed.error ?? 'not sent')}`,
state: 'degraded',
})
return result
}
// Graph selected but unavailable is a configuration problem even if SMTP delivered.
await recordIntegrationStatus(
payload,
STATUS_FIELD,
previous,
large && support === 'no-permission'
? { code: 'graph-large-files', state: 'degraded' }
: graphFallback
? {
code: 'graph-unavailable',
message:
'Microsoft Graph is selected but not set up on the server, so e-mails go over SMTP. Ask your administrator.',
state: 'degraded',
}
: { state: 'ok' },
)
return result
}
}