import type { PayloadEmailAdapter, SendEmailOptions } from 'payload' import { type IntegrationStatus, recordIntegrationStatus } from '../integrations/status.js' import { getSiteIntegrations } from '../payload/index.js' import { graphAdapter, type GraphAdapterArgs, graphLargeAttachmentSupport } from './graphAdapter.js' import { attachmentBytes, GRAPH_INLINE_MAX_BYTES, toGraphAttachments } from './graphAttachments.js' import { panelSmtpAdapter, type PanelSmtpAdapterArgs } from './panelSmtpAdapter.js' type TransportIntegrations = { emailStatus?: IntegrationStatus | null /** 'smtp' | 'graph' — chosen by the editor in SiteIntegrations. */ emailTransport?: 'graph' | 'smtp' | null smtpHost?: null | string smtpPassword?: null | string smtpUser?: null | string } const smtpConfigured = (s: TransportIntegrations) => Boolean(s.smtpHost && s.smtpUser && s.smtpPassword) /** 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']) 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 graph?: GraphAdapterArgs smtp?: PanelSmtpAdapterArgs } /** True when the agency Graph credentials are present in the environment. */ 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 * (SMTP or Graph) per send by reading `emailTransport` from SiteIntegrations. * 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) => { // 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 attachmentLimit = async (): Promise => { const settings = await getSiteIntegrations(payload) if ((settings.emailTransport ?? 'smtp') !== 'graph' || !graphAvailable()) {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) => { const settings = await getSiteIntegrations(payload) const choice = settings.emailTransport ?? 'smtp' const previous = settings[STATUS_FIELD] const useGraph = choice === 'graph' && graphAvailable() const graphFallback = 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( '[ipal] Transport set to Graph but GRAPH_* env vars are missing; falling back to SMTP.', ) } // 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' const code = viaGraph ? 'graph-error' : '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 }, } }