import type { EmailAdapter, SendEmailOptions } from 'payload' // Sends Payload's email (password resets, form notifications) through // exe.dev's email gateway: no provider, no password. It delivers plain // text to the VM's owner, their team, and people the VM is shared with. // https://exe.dev/docs/send-email // From https://exe.dev/deploy/payload const GATEWAY = 'http://169.254.169.254/gateway/email/send' type Recipient = string | { address: string; name?: string } // "Ann , bob@example.com" or address objects -> bare addresses const recipients = (to: SendEmailOptions['to']): string[] => ([] as Recipient[]) .concat((to ?? []) as Recipient | Recipient[]) .flatMap((r) => (typeof r === 'string' ? r.split(',') : [r.address])) .map((a) => (a.match(/<([^>]+)>/)?.[1] ?? a).trim()) .filter(Boolean) // Plain text from Payload's HTML emails, keeping link addresses. const toText = (html: string) => html .replace(/]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi, (_: string, href: string, text: string) => text.trim() === href ? href : `${text} (${href})`, ) .replace(//gi, '\n') .replace(/<\/(p|h[1-6])>/gi, '\n\n') .replace(/<\/(div|li|tr)>/gi, '\n') .replace(/<[^>]+>/g, '') .replace(/ /g, ' ') .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"') .replace(/'/g, "'") .replace(/&/g, '&') .replace(/[ \t]+\n/g, '\n') .replace(/\n{3,}/g, '\n\n') .trim() export const exedevEmail: EmailAdapter = () => ({ name: 'exe.dev', defaultFromAddress: 'payload@exe.dev', // the gateway sends from its own address defaultFromName: 'Payload', sendEmail: async (message) => { const body = typeof message.text === 'string' && message.text ? message.text : toText(String(message.html ?? '')) for (const to of recipients(message.to)) { const res = await fetch(GATEWAY, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ to, subject: message.subject ?? '', body }), }) if (!res.ok) throw new Error(`exe.dev email to ${to} failed: ${res.status} ${await res.text()}`) } }, })