import 'server-only' import type { BasePayload } from 'payload' import nodemailer from 'nodemailer' import { getSiteIntegrations } from '../payload/index.js' /** SMTP fields the sender reads from SiteIntegrations. */ type SmtpIntegrations = { smtpFromAddress?: null | string smtpFromName?: null | string smtpHost?: null | string smtpPassword?: null | string smtpPort?: null | number smtpUser?: null | string } export type SendEmailArgs = { /** Override the configured from-address for this message. */ from?: string /** HTML body. */ html: string /** Payload instance — used to read SMTP config from SiteIntegrations. */ payload: BasePayload replyTo?: string subject: string /** Optional plain-text fallback. */ text?: string to: string | string[] } export type SendEmailResult = { error: string; sent: false } | { messageId: string; sent: true } /** * Sends an email using SMTP settings from the SiteIntegrations global. * * Reads config at call time (not at boot) so editors can change SMTP in the * admin panel without a restart — consistent with the plugin's panel-managed * model. `server-only` keeps the SMTP password out of any client bundle. * * Returns a result object rather than throwing, so callers (e.g. form * submission) can handle failure without a try/catch and never leak SMTP * details to the client. */ export async function sendEmail({ from, html, payload, replyTo, subject, text, to, }: SendEmailArgs): Promise { const smtp = await getSiteIntegrations(payload) const host = smtp.smtpHost const port = smtp.smtpPort ?? 587 const user = smtp.smtpUser const pass = smtp.smtpPassword if (!host || !user || !pass) { return { error: 'Fill in the server, user name and password.', sent: false } } const fromAddress = from ?? smtp.smtpFromAddress if (!fromAddress) { return { error: 'Fill in the sender address.', sent: false } } const fromName = smtp.smtpFromName const fromHeader = fromName ? `${fromName} <${fromAddress}>` : fromAddress const transporter = nodemailer.createTransport({ auth: { pass, user }, host, port, secure: port === 465, // implicit TLS on 465, STARTTLS otherwise }) try { const info = await transporter.sendMail({ from: fromHeader, html, subject, to, ...(text ? { text } : {}), ...(replyTo ? { replyTo } : {}), }) return { messageId: info.messageId, sent: true } } catch (err) { payload.logger.error(`[iapl] Email send failed: ${(err as Error).message}`) return { error: 'The e-mail was not sent.', sent: false } } }