| 1 | import type { Transport } from 'nodemailer'; |
| 2 | import type MailMessage from 'nodemailer/lib/mailer/mail-message.js'; |
| 3 | |
| 4 | function addresses(value: unknown): string { |
| 5 | if (typeof value === 'string') return value; |
| 6 | if (Array.isArray(value)) return value.map(addresses).join(', '); |
| 7 | if (value && typeof value === 'object' && 'address' in value) { |
| 8 | return (value as { address: string }).address; |
| 9 | } |
| 10 | return ''; |
| 11 | } |
| 12 | |
| 13 | /** Nodemailer transport that POSTs the rendered mail to an HTTP relay instead of talking SMTP, for deployments where outbound port 587 is closed. */ |
| 14 | export function proxyTransport(url: string, secret?: string): Transport { |
| 15 | return { |
| 16 | name: 'email-proxy', |
| 17 | version: '1.0.0', |
| 18 | send(mail: MailMessage, callback) { |
| 19 | const { to, from, subject, html, text } = mail.data; |
| 20 | fetch(url, { |
| 21 | method: 'POST', |
| 22 | headers: { 'Content-Type': 'application/json' }, |
| 23 | body: JSON.stringify({ |
| 24 | to: addresses(to), |
| 25 | from: addresses(from), |
| 26 | subject, |
| 27 | htmlBody: html, |
| 28 | textBody: text, |
| 29 | secret, |
| 30 | }), |
| 31 | }) |
| 32 | .then(async (res) => { |
| 33 | if (!res.ok) { |
| 34 | throw new Error( |
| 35 | `Email proxy responded with ${res.status}: ${await res.text()}`, |
| 36 | ); |
| 37 | } |
| 38 | callback(null, { |
| 39 | envelope: mail.message!.getEnvelope(), |
| 40 | messageId: mail.message!.messageId(), |
| 41 | }); |
| 42 | }) |
| 43 | .catch((error: Error) => callback(error, undefined)); |
| 44 | }, |
| 45 | }; |
| 46 | } |