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]>
This commit is contained in:
Radosław Smoliński
2026-11-26 22:39:03 +01:00
co-authored by Claude Fable 5.2
parent c6841a1674
commit ee8ea42956
26 changed files with 376 additions and 138 deletions
+10 -9
View File
@@ -1,19 +1,20 @@
import type { PayloadEmailAdapter, SendEmailOptions } from 'payload'
import { type IntegrationStatus, recordIntegrationStatus } from '../integrations/status.js'
import { getSiteIntegrations } from '../payload/index.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 { getMailMethod, type MailMethod } from './method.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 = {
emailStatus?: IntegrationStatus | null
/** '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
@@ -59,7 +60,7 @@ export type ResolvedMailMethod = {
}
/**
* The sending method in effect. With a choice (`getMailMethod`): exactly that method — an SMTP choice with
* 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
@@ -164,11 +165,11 @@ export const mailAdapter =
* without SMTP settings the ceiling is GRAPH_INLINE_MAX_BYTES.
*/
const relayOptions = () => resolveRelayOptions(payload, args.relay)
const methodOf = async (settings: TransportIntegrations) => resolveMailMethod(settings, { chosen: await getMailMethod(payload), graphEnv: graphAvailable(), relay: Boolean(relayOptions()) })
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 getSiteIntegrations<TransportIntegrations>(payload)
const transport = (await methodOf(settings)).method
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}
@@ -192,10 +193,10 @@ export const mailAdapter =
}
async function send(message: SendEmailOptions): Promise<unknown> {
const settings = await getSiteIntegrations<TransportIntegrations>(payload)
const settings = await readMailSettings<TransportIntegrations>(payload)
const choice = settings.emailTransport ?? 'smtp'
const previous = settings[STATUS_FIELD]
const resolved = await methodOf(settings)
const resolved = methodOf(settings)
const chosen = resolved.method
// No SMTP server in the panel and no Graph: the Intecion Notifications Webservice.
+24 -25
View File
@@ -1,49 +1,48 @@
import type { BasePayload } from 'payload'
import { findSiteIntegrations, MAIL_METHOD_FIELD, SITE_INTEGRATIONS_SLUG } from '../payload/getSiteIntegrations.js'
/**
* The sending method an admin chose in Site integrations → E-mail sending ("Sending method"):
* the built-in service (IWSN), the client's own SMTP server, or Microsoft Graph (deprecated).
*
* Where it is stored: in Payload's key-value store (`payload-kv`), under `MAIL_METHOD_KV_KEY` — not in
* a column of the global. The global's stored field `emailTransport` has two values since 1.6 (`smtp`,
* `graph`); a third would change the Postgres enum and ask every SQL project for a migration, and it
* still could not tell "SMTP was chosen" from the `smtp` that every site has stored since before the
* choice existed. So the panel's field (`emailMethod`) is virtual, and the choice lives here.
* Stored in the global's field `emailMethod` (a select, new in 1.17.1; Postgres / SQLite: one migration).
* Empty = nobody has chosen yet (a site upgraded from 1.17.0 or older, a new site): the method follows the
* order of 1.17.0 (`resolveMailTransport`) and the panel shows it as selected. The first save of the panel's
* form — or `setMailMethod()` — stores the choice; from then on what is chosen is what is used.
*
* No entry = nobody has chosen yet (a site upgraded from 1.17.0 or older, a new site): the method follows
* the order of 1.17.0 (`resolveMailTransport`) and the panel shows it as selected. The first save of Site
* integrations — or `setMailMethod()` — writes the choice; from then on what is chosen is what is used.
* Why a field of its own and not a third value in `emailTransport` (`smtp` / `graph`, stored since 1.6):
* every site has `smtp` stored there from before there was a choice, so "SMTP was chosen" could not be told
* from "nothing was chosen" — and an upgrade must keep a site with no SMTP server on the service.
*/
export type MailMethod = 'graph' | 'relay' | 'smtp'
export const MAIL_METHODS: readonly MailMethod[] = ['relay', 'smtp', 'graph']
export const MAIL_METHOD_KV_KEY = 'iapl:mail-method'
/**
* A read with this key in its `context` gets `emailMethod` as stored (empty when nobody chose) — not the
* method the panel shows as selected.
*/
export const STORED_MAIL_METHOD_CONTEXT = 'iaplStoredMailMethod'
export const isMailMethod = (value: unknown): value is MailMethod => typeof value === 'string' && (MAIL_METHODS as readonly string[]).includes(value)
type Kv = { delete?: (key: string) => Promise<unknown>; get?: (key: string) => Promise<unknown>; set?: (key: string, value: object) => Promise<unknown> }
const kvOf = (payload: Pick<BasePayload, 'kv'>): Kv => ((payload as { kv?: Kv }).kv ?? {})
/** Site integrations with `emailMethod` as stored — what the mail adapter and the state block decide from. */
export function readMailSettings<T = Record<string, unknown>>(payload: BasePayload): Promise<T> {
return findSiteIntegrations<T>(payload, { context: { [STORED_MAIL_METHOD_CONTEXT]: true } })
}
/** The chosen method, or null when nobody has chosen yet. Reads only. */
export async function getMailMethod(payload: Pick<BasePayload, 'kv'>): Promise<MailMethod | null> {
const kv = kvOf(payload)
if (typeof kv.get !== 'function') {return null}
const stored = (await kv.get(MAIL_METHOD_KV_KEY)) as { method?: unknown } | null
return isMailMethod(stored?.method) ? stored.method : null
export async function getMailMethod(payload: BasePayload): Promise<MailMethod | null> {
const stored = (await readMailSettings<Record<string, unknown>>(payload))[MAIL_METHOD_FIELD]
return isMailMethod(stored) ? stored : null
}
/**
* Chooses the method (a seed, a deploy script; the panel does it on save). `null` = nobody has chosen:
* the order of 1.17.0 applies again.
*/
export async function setMailMethod(payload: Pick<BasePayload, 'kv'>, method: MailMethod | null): Promise<void> {
const kv = kvOf(payload)
if (method === null) {
await kv.delete?.(MAIL_METHOD_KV_KEY)
return
}
if (!isMailMethod(method)) {throw new Error(`[iapl] setMailMethod: "${String(method)}" is not a sending method (relay, smtp, graph).`)}
if (typeof kv.set !== 'function') {throw new Error('[iapl] setMailMethod: this Payload has no key-value store (payload.kv).')}
await kv.set(MAIL_METHOD_KV_KEY, { at: new Date().toISOString(), method })
export async function setMailMethod(payload: BasePayload, method: MailMethod | null): Promise<void> {
if (method !== null && !isMailMethod(method)) {throw new Error(`[iapl] setMailMethod: "${String(method)}" is not a sending method (relay, smtp, graph).`)}
await payload.updateGlobal({ slug: SITE_INTEGRATIONS_SLUG as never, data: { [MAIL_METHOD_FIELD]: method } as never, overrideAccess: true })
}
+8 -4
View File
@@ -5,9 +5,9 @@ import type { RelayOptions } from './options.js'
import { userMeetsRole } from '../../access/predicates.js'
import { serverText } from '../../integrations/texts.js'
import { getSiteIntegrations } from '../../payload/index.js'
import { mailMethodColumnMissing } from '../../payload/getSiteIntegrations.js'
import { graphAvailable, type MailMethodProblem, type MailTransport, resolveMailMethod, smtpIncomplete } from '../mailAdapter.js'
import { getMailMethod } from '../method.js'
import { isMailMethod, readMailSettings } from '../method.js'
import { RELAY_SENDER_ADDRESS } from './adapter.js'
import { relayRequest } from './client.js'
import { RELAY_CONFIRM_PATH, RELAY_CONNECT_PATH, RELAY_DISCONNECT_PATH, RELAY_STATUS_PATH } from './constants.js'
@@ -16,6 +16,7 @@ import { disconnectRelay, enrolRelay, type EnrolResult, getRelayStatus, LOCAL_CO
import { otherRelayHosts } from './store.js'
type Settings = {
emailMethod?: null | string
emailStatus?: IntegrationStatus | null
emailTransport?: 'graph' | 'smtp' | null
smtpFromAddress?: null | string
@@ -35,6 +36,8 @@ export type MailPanelState = {
* method follows the order of 1.17.0 until Site integrations is saved.
*/
methodChosen: boolean
/** Postgres / SQLite: the column of "Sending method" is missing (the 1.17.1 migration has not run); the order of 1.17.0 applies. */
methodColumnMissing?: boolean
/** The chosen method cannot be used; e-mails are NOT sent another way. */
methodProblem?: MailMethodProblem
/** The site is not public: its host is a development address (`developmentHosts`), or `IAPL_NOINDEX` is set. */
@@ -66,9 +69,9 @@ function refuse(req: PayloadRequest): null | Response {
/** The transport in effect and the site's state with the service, for the panel and the doctor. */
export async function mailPanelState(req: Pick<PayloadRequest, 'payload'>, own: false | RelayOptions | undefined, { refresh = false }: { refresh?: boolean } = {}): Promise<MailPanelState> {
const { payload } = req
const settings = await getSiteIntegrations<Settings>(payload)
const settings = await readMailSettings<Settings>(payload)
const options = resolveRelayOptions(payload, own)
const method = resolveMailMethod(settings, { chosen: await getMailMethod(payload), graphEnv: graphAvailable(), relay: Boolean(options) })
const method = resolveMailMethod(settings, { chosen: isMailMethod(settings.emailMethod) ? settings.emailMethod : null, graphEnv: graphAvailable(), relay: Boolean(options) })
const transport = method.method
let status = options ? await getRelayStatus(payload, options, { refresh: refresh && transport === 'relay' }) : null
// A site the service could never call back (it runs locally, or does not know its address) is refused by the
@@ -98,6 +101,7 @@ export async function mailPanelState(req: Pick<PayloadRequest, 'payload'>, own:
...(options?.accessKeyField === true ? { accessKeyField: true } : {}),
...(status?.host ? { confirmUrl: `https://${status.host}${api}${RELAY_CONFIRM_PATH}` } : {}),
methodChosen: method.explicit,
...(mailMethodColumnMissing() ? { methodColumnMissing: true } : {}),
...(method.problem ? { methodProblem: method.problem } : {}),
relay: status ? { ...status, senderAddress: status.senderAddress ?? RELAY_SENDER_ADDRESS } : null,
replyAddress: typeof settings.smtpFromAddress === 'string' && settings.smtpFromAddress.trim() ? settings.smtpFromAddress.trim() : null,