email.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  1. import nodemailer from 'nodemailer'
  2. import { Resend } from 'resend'
  3. import { ServerClient as PostmarkClient } from 'postmark'
  4. import Mailgun from 'mailgun.js'
  5. import FormData from 'form-data'
  6. import sgMail, { type MailDataRequired } from '@sendgrid/mail'
  7. import { SESClient, SendRawEmailCommand } from '@aws-sdk/client-ses'
  8. import {
  9. asLegacyMap,
  10. channelProvider,
  11. channelSettings,
  12. legacyProviderNamed,
  13. } from '@/features/integrations/Lib/messaging'
  14. import { messagingProvider } from '@/integrations/messaging/catalog'
  15. import { db } from './db'
  16. import { formatMailAddress, parseMailAddress } from './email-address'
  17. import { SYSTEM_SETTING_KEYS } from '@/features/admin/Schema/systemSettingsSchema'
  18. import { ORG_EMAIL_KEYS } from '@/features/email/Schema/emailSettingsSchema'
  19. export type EmailProvider = 'smtp' | 'resend' | 'postmark' | 'mailgun' | 'sendgrid' | 'ses'
  20. export interface SendMailOptions {
  21. from: string
  22. to: string
  23. /**
  24. * Where a reply should go when it is not the sender. A support request goes
  25. * out from the platform address, so without this the administrator's reply
  26. * button addresses the platform itself rather than the person asking.
  27. */
  28. replyTo?: string
  29. subject: string
  30. html: string
  31. /**
  32. * The plain-text half of the mail. A message with no text part scores worse
  33. * with spam filters, and some people read mail as text on purpose. Every
  34. * provider below takes one; the document mails generate theirs from the
  35. * same spec the HTML comes from, so the two cannot disagree.
  36. */
  37. text?: string
  38. attachments?: {
  39. filename: string
  40. content: Buffer
  41. }[]
  42. /**
  43. * Threading headers, for a mail a customer may answer. The Message-ID is
  44. * ours (without angle brackets) so a reply's In-Reply-To names something
  45. * we stored; In-Reply-To and References point a reply of ours at the
  46. * customer's mail so their client files it in the same conversation.
  47. */
  48. messageId?: string
  49. inReplyTo?: string
  50. references?: string[]
  51. }
  52. const bracketed = (id: string) => (id.startsWith('<') ? id : `<${id}>`)
  53. /** The threading headers as a mail API wants them, with angle brackets on. */
  54. function threadHeaders(options: SendMailOptions): Record<string, string> {
  55. const headers: Record<string, string> = {}
  56. if (options.messageId) headers['Message-ID'] = bracketed(options.messageId)
  57. if (options.inReplyTo) headers['In-Reply-To'] = bracketed(options.inReplyTo)
  58. if (options.references?.length) {
  59. headers.References = options.references.map(bracketed).join(' ')
  60. }
  61. return headers
  62. }
  63. /** The same headers in nodemailer's own fields. */
  64. function nodemailerThreading(options: SendMailOptions) {
  65. return {
  66. messageId: options.messageId ? bracketed(options.messageId) : undefined,
  67. inReplyTo: options.inReplyTo ? bracketed(options.inReplyTo) : undefined,
  68. references: options.references?.length ? options.references.map(bracketed) : undefined,
  69. }
  70. }
  71. // ─── Settings map helper ────────────────────────────────────────────────────
  72. type SettingsMap = Map<string, string>
  73. async function getSystemSettings(keys: string[]): Promise<SettingsMap> {
  74. const rows = await db.systemSetting.findMany({
  75. where: { key: { in: keys } },
  76. })
  77. return new Map(rows.map((r) => [r.key, r.value]))
  78. }
  79. // ─── System-level helpers (read from SystemSetting + env) ───────────────────
  80. async function getEmailProvider(): Promise<EmailProvider> {
  81. const setting = await db.systemSetting.findUnique({
  82. where: { key: SYSTEM_SETTING_KEYS.EMAIL_PROVIDER },
  83. })
  84. const value = setting?.value
  85. if (
  86. value === 'resend' ||
  87. value === 'postmark' ||
  88. value === 'mailgun' ||
  89. value === 'sendgrid' ||
  90. value === 'ses'
  91. ) {
  92. return value
  93. }
  94. return 'smtp'
  95. }
  96. export async function getFromAddress(): Promise<string> {
  97. const provider = await getEmailProvider()
  98. const keyMap: Record<EmailProvider, { email: string; name: string }> = {
  99. smtp: {
  100. email: SYSTEM_SETTING_KEYS.SMTP_FROM_EMAIL,
  101. name: SYSTEM_SETTING_KEYS.SMTP_FROM_NAME,
  102. },
  103. resend: {
  104. email: SYSTEM_SETTING_KEYS.RESEND_FROM_EMAIL,
  105. name: SYSTEM_SETTING_KEYS.RESEND_FROM_NAME,
  106. },
  107. postmark: {
  108. email: SYSTEM_SETTING_KEYS.POSTMARK_FROM_EMAIL,
  109. name: SYSTEM_SETTING_KEYS.POSTMARK_FROM_NAME,
  110. },
  111. mailgun: {
  112. email: SYSTEM_SETTING_KEYS.MAILGUN_FROM_EMAIL,
  113. name: SYSTEM_SETTING_KEYS.MAILGUN_FROM_NAME,
  114. },
  115. sendgrid: {
  116. email: SYSTEM_SETTING_KEYS.SENDGRID_FROM_EMAIL,
  117. name: SYSTEM_SETTING_KEYS.SENDGRID_FROM_NAME,
  118. },
  119. ses: {
  120. email: SYSTEM_SETTING_KEYS.SES_FROM_EMAIL,
  121. name: SYSTEM_SETTING_KEYS.SES_FROM_NAME,
  122. },
  123. }
  124. const keys = keyMap[provider]
  125. const rows = await db.systemSetting.findMany({
  126. where: { key: { in: [keys.email, keys.name] } },
  127. })
  128. const map = new Map(rows.map((r) => [r.key, r.value]))
  129. const fromEmail = map.get(keys.email) || process.env.SMTP_FROM_EMAIL || 'noreply@example.com'
  130. const fromName = map.get(keys.name) || 'Torqvoice'
  131. return `${fromName} <${fromEmail}>`
  132. }
  133. // ─── SMTP ──────────────────────────────────────────────────────────────────
  134. interface SmtpConfig {
  135. host: string
  136. port: number
  137. user?: string
  138. pass?: string
  139. secure: boolean
  140. rejectUnauthorized: boolean
  141. requireTls: boolean
  142. }
  143. function buildSmtpConfig(
  144. settings: SettingsMap,
  145. keys: {
  146. host: string
  147. port: string
  148. user: string
  149. pass: string
  150. secure: string
  151. rejectUnauthorized: string
  152. requireTls: string
  153. },
  154. useEnvFallback: boolean
  155. ): SmtpConfig {
  156. const host = settings.get(keys.host) || (useEnvFallback ? process.env.SMTP_HOST : undefined)
  157. const port =
  158. Number(settings.get(keys.port)) || (useEnvFallback ? Number(process.env.SMTP_PORT) : 0) || 587
  159. const user = settings.get(keys.user) || (useEnvFallback ? process.env.SMTP_USER : undefined)
  160. const pass = settings.get(keys.pass) || (useEnvFallback ? process.env.SMTP_PASS : undefined)
  161. const secureSetting = settings.get(keys.secure)
  162. const secure =
  163. secureSetting !== undefined
  164. ? secureSetting === 'true'
  165. : useEnvFallback
  166. ? process.env.SMTP_SECURE === 'true'
  167. : false
  168. const rejectSetting = settings.get(keys.rejectUnauthorized)
  169. const rejectUnauthorized =
  170. rejectSetting !== undefined
  171. ? rejectSetting !== 'false'
  172. : useEnvFallback
  173. ? process.env.SMTP_REJECT_UNAUTHORIZED !== 'false'
  174. : true
  175. const requireTlsSetting = settings.get(keys.requireTls)
  176. const requireTls = requireTlsSetting === 'true'
  177. if (!host) {
  178. throw new Error('SMTP is not configured. Configure SMTP in your email settings.')
  179. }
  180. return { host, port, user, pass, secure, rejectUnauthorized, requireTls }
  181. }
  182. function createSmtpTransporter(config: SmtpConfig) {
  183. return nodemailer.createTransport({
  184. host: config.host,
  185. port: config.port,
  186. secure: config.secure,
  187. auth: config.user
  188. ? {
  189. user: config.user,
  190. pass: config.pass,
  191. }
  192. : undefined,
  193. tls: {
  194. rejectUnauthorized: config.rejectUnauthorized,
  195. },
  196. requireTLS: config.requireTls,
  197. })
  198. }
  199. async function sendViaSmtpWithSettings(
  200. options: SendMailOptions,
  201. settings: SettingsMap,
  202. keys: {
  203. host: string
  204. port: string
  205. user: string
  206. pass: string
  207. secure: string
  208. rejectUnauthorized: string
  209. requireTls: string
  210. },
  211. useEnvFallback: boolean
  212. ) {
  213. const config = buildSmtpConfig(settings, keys, useEnvFallback)
  214. const transporter = createSmtpTransporter(config)
  215. await transporter.sendMail({
  216. from: options.from,
  217. to: options.to,
  218. replyTo: options.replyTo,
  219. subject: options.subject,
  220. html: options.html,
  221. text: options.text,
  222. attachments: options.attachments?.map((a) => ({
  223. filename: a.filename,
  224. content: a.content,
  225. })),
  226. ...nodemailerThreading(options),
  227. })
  228. }
  229. async function sendViaSmtp(options: SendMailOptions) {
  230. const keys = [
  231. SYSTEM_SETTING_KEYS.SMTP_HOST,
  232. SYSTEM_SETTING_KEYS.SMTP_PORT,
  233. SYSTEM_SETTING_KEYS.SMTP_USER,
  234. SYSTEM_SETTING_KEYS.SMTP_PASS,
  235. SYSTEM_SETTING_KEYS.SMTP_SECURE,
  236. SYSTEM_SETTING_KEYS.SMTP_REJECT_UNAUTHORIZED,
  237. SYSTEM_SETTING_KEYS.SMTP_REQUIRE_TLS,
  238. ]
  239. const settings = await getSystemSettings(keys)
  240. await sendViaSmtpWithSettings(
  241. options,
  242. settings,
  243. {
  244. host: SYSTEM_SETTING_KEYS.SMTP_HOST,
  245. port: SYSTEM_SETTING_KEYS.SMTP_PORT,
  246. user: SYSTEM_SETTING_KEYS.SMTP_USER,
  247. pass: SYSTEM_SETTING_KEYS.SMTP_PASS,
  248. secure: SYSTEM_SETTING_KEYS.SMTP_SECURE,
  249. rejectUnauthorized: SYSTEM_SETTING_KEYS.SMTP_REJECT_UNAUTHORIZED,
  250. requireTls: SYSTEM_SETTING_KEYS.SMTP_REQUIRE_TLS,
  251. },
  252. true
  253. )
  254. }
  255. // ─── Resend ────────────────────────────────────────────────────────────────
  256. async function sendViaResendWithSettings(
  257. options: SendMailOptions,
  258. settings: SettingsMap,
  259. apiKeyField: string
  260. ) {
  261. const apiKey = settings.get(apiKeyField)
  262. if (!apiKey) {
  263. throw new Error('Resend is not configured. Add your Resend API key.')
  264. }
  265. const resend = new Resend(apiKey)
  266. const headers = threadHeaders(options)
  267. await resend.emails.send({
  268. from: options.from,
  269. to: options.to,
  270. replyTo: options.replyTo,
  271. subject: options.subject,
  272. html: options.html,
  273. text: options.text,
  274. attachments: options.attachments?.map((a) => ({
  275. filename: a.filename,
  276. content: a.content,
  277. })),
  278. ...(Object.keys(headers).length > 0 && { headers }),
  279. })
  280. }
  281. async function sendViaResend(options: SendMailOptions) {
  282. const settings = await getSystemSettings([SYSTEM_SETTING_KEYS.RESEND_API_KEY])
  283. await sendViaResendWithSettings(options, settings, SYSTEM_SETTING_KEYS.RESEND_API_KEY)
  284. }
  285. // ─── Postmark ──────────────────────────────────────────────────────────────
  286. async function sendViaPostmarkWithSettings(
  287. options: SendMailOptions,
  288. settings: SettingsMap,
  289. apiKeyField: string
  290. ) {
  291. const apiKey = settings.get(apiKeyField)
  292. if (!apiKey) {
  293. throw new Error('Postmark is not configured. Add your Server Token.')
  294. }
  295. const client = new PostmarkClient(apiKey)
  296. const headers = Object.entries(threadHeaders(options)).map(([Name, Value]) => ({ Name, Value }))
  297. const Headers = headers.length > 0 ? headers : undefined
  298. if (options.attachments?.length) {
  299. await client.sendEmail({
  300. From: options.from,
  301. To: options.to,
  302. ReplyTo: options.replyTo,
  303. Subject: options.subject,
  304. HtmlBody: options.html,
  305. TextBody: options.text,
  306. Headers,
  307. Attachments: options.attachments.map((a) => ({
  308. Name: a.filename,
  309. Content: a.content.toString('base64'),
  310. ContentType: 'application/octet-stream',
  311. ContentID: '',
  312. })),
  313. })
  314. } else {
  315. await client.sendEmail({
  316. From: options.from,
  317. To: options.to,
  318. ReplyTo: options.replyTo,
  319. Subject: options.subject,
  320. HtmlBody: options.html,
  321. TextBody: options.text,
  322. Headers,
  323. })
  324. }
  325. }
  326. async function sendViaPostmark(options: SendMailOptions) {
  327. const settings = await getSystemSettings([SYSTEM_SETTING_KEYS.POSTMARK_API_KEY])
  328. await sendViaPostmarkWithSettings(options, settings, SYSTEM_SETTING_KEYS.POSTMARK_API_KEY)
  329. }
  330. // ─── Mailgun ───────────────────────────────────────────────────────────────
  331. async function sendViaMailgunWithSettings(
  332. options: SendMailOptions,
  333. settings: SettingsMap,
  334. keys: { apiKey: string; domain: string; region: string }
  335. ) {
  336. const apiKey = settings.get(keys.apiKey)
  337. const domain = settings.get(keys.domain)
  338. const region = settings.get(keys.region) || 'us'
  339. if (!apiKey || !domain) {
  340. throw new Error('Mailgun is not configured. Add your API key and domain.')
  341. }
  342. const mailgun = new Mailgun(FormData)
  343. const mg = mailgun.client({
  344. username: 'api',
  345. key: apiKey,
  346. url: region === 'eu' ? 'https://api.eu.mailgun.net' : undefined,
  347. })
  348. const headers = Object.fromEntries(
  349. Object.entries(threadHeaders(options)).map(([name, value]) => [`h:${name}`, value])
  350. )
  351. await mg.messages.create(domain, {
  352. from: options.from,
  353. to: [options.to],
  354. ...(options.replyTo && { 'h:Reply-To': options.replyTo }),
  355. ...headers,
  356. subject: options.subject,
  357. html: options.html,
  358. ...(options.text && { text: options.text }),
  359. ...(options.attachments?.length && {
  360. attachment: options.attachments.map((a) => ({
  361. filename: a.filename,
  362. data: a.content,
  363. })),
  364. }),
  365. })
  366. }
  367. async function sendViaMailgun(options: SendMailOptions) {
  368. const keys = [
  369. SYSTEM_SETTING_KEYS.MAILGUN_API_KEY,
  370. SYSTEM_SETTING_KEYS.MAILGUN_DOMAIN,
  371. SYSTEM_SETTING_KEYS.MAILGUN_REGION,
  372. ]
  373. const settings = await getSystemSettings(keys)
  374. await sendViaMailgunWithSettings(options, settings, {
  375. apiKey: SYSTEM_SETTING_KEYS.MAILGUN_API_KEY,
  376. domain: SYSTEM_SETTING_KEYS.MAILGUN_DOMAIN,
  377. region: SYSTEM_SETTING_KEYS.MAILGUN_REGION,
  378. })
  379. }
  380. // ─── SendGrid ──────────────────────────────────────────────────────────────
  381. async function sendViaSendGridWithSettings(
  382. options: SendMailOptions,
  383. settings: SettingsMap,
  384. apiKeyField: string
  385. ) {
  386. const apiKey = settings.get(apiKeyField)
  387. if (!apiKey) {
  388. throw new Error('SendGrid is not configured. Add your API key.')
  389. }
  390. sgMail.setApiKey(apiKey)
  391. const headers = threadHeaders(options)
  392. const msg: MailDataRequired = {
  393. from: options.from,
  394. to: options.to,
  395. replyTo: options.replyTo,
  396. subject: options.subject,
  397. html: options.html,
  398. ...(options.text && { text: options.text }),
  399. ...(Object.keys(headers).length > 0 && { headers }),
  400. }
  401. if (options.attachments?.length) {
  402. msg.attachments = options.attachments.map((a) => ({
  403. filename: a.filename,
  404. content: a.content.toString('base64'),
  405. type: 'application/octet-stream',
  406. disposition: 'attachment' as const,
  407. }))
  408. }
  409. await sgMail.send(msg)
  410. }
  411. async function sendViaSendGrid(options: SendMailOptions) {
  412. const settings = await getSystemSettings([SYSTEM_SETTING_KEYS.SENDGRID_API_KEY])
  413. await sendViaSendGridWithSettings(options, settings, SYSTEM_SETTING_KEYS.SENDGRID_API_KEY)
  414. }
  415. // ─── Amazon SES ────────────────────────────────────────────────────────────
  416. async function sendViaSesWithSettings(
  417. options: SendMailOptions,
  418. settings: SettingsMap,
  419. keys: { accessKeyId: string; secretAccessKey: string; region: string }
  420. ) {
  421. const accessKeyId = settings.get(keys.accessKeyId)
  422. const secretAccessKey = settings.get(keys.secretAccessKey)
  423. const region = settings.get(keys.region) || 'us-east-1'
  424. if (!accessKeyId || !secretAccessKey) {
  425. throw new Error('Amazon SES is not configured. Add your credentials.')
  426. }
  427. const transporter = nodemailer.createTransport({ streamTransport: true })
  428. const info = await transporter.sendMail({
  429. from: options.from,
  430. to: options.to,
  431. replyTo: options.replyTo,
  432. subject: options.subject,
  433. html: options.html,
  434. text: options.text,
  435. attachments: options.attachments?.map((a) => ({
  436. filename: a.filename,
  437. content: a.content,
  438. })),
  439. ...nodemailerThreading(options),
  440. })
  441. const rawMessage = Buffer.isBuffer(info.message)
  442. ? info.message
  443. : await streamToBuffer(info.message)
  444. const client = new SESClient({
  445. region,
  446. credentials: { accessKeyId, secretAccessKey },
  447. })
  448. await client.send(new SendRawEmailCommand({ RawMessage: { Data: rawMessage } }))
  449. }
  450. async function sendViaSes(options: SendMailOptions) {
  451. const keys = [
  452. SYSTEM_SETTING_KEYS.SES_ACCESS_KEY_ID,
  453. SYSTEM_SETTING_KEYS.SES_SECRET_ACCESS_KEY,
  454. SYSTEM_SETTING_KEYS.SES_REGION,
  455. ]
  456. const settings = await getSystemSettings(keys)
  457. await sendViaSesWithSettings(options, settings, {
  458. accessKeyId: SYSTEM_SETTING_KEYS.SES_ACCESS_KEY_ID,
  459. secretAccessKey: SYSTEM_SETTING_KEYS.SES_SECRET_ACCESS_KEY,
  460. region: SYSTEM_SETTING_KEYS.SES_REGION,
  461. })
  462. }
  463. function streamToBuffer(stream: NodeJS.ReadableStream): Promise<Uint8Array> {
  464. return new Promise((resolve, reject) => {
  465. const chunks: Buffer[] = []
  466. stream.on('data', (chunk: Buffer) => chunks.push(chunk))
  467. stream.on('end', () => resolve(Buffer.concat(chunks)))
  468. stream.on('error', reject)
  469. })
  470. }
  471. // ─── Provider dispatch (shared by both system and org) ──────────────────────
  472. function sendWithProvider(
  473. provider: EmailProvider,
  474. options: SendMailOptions,
  475. settings: SettingsMap,
  476. keySet: 'system' | 'org'
  477. ) {
  478. if (keySet === 'org') {
  479. switch (provider) {
  480. case 'smtp':
  481. return sendViaSmtpWithSettings(
  482. options,
  483. settings,
  484. {
  485. host: ORG_EMAIL_KEYS.EMAIL_SMTP_HOST,
  486. port: ORG_EMAIL_KEYS.EMAIL_SMTP_PORT,
  487. user: ORG_EMAIL_KEYS.EMAIL_SMTP_USER,
  488. pass: ORG_EMAIL_KEYS.EMAIL_SMTP_PASS,
  489. secure: ORG_EMAIL_KEYS.EMAIL_SMTP_SECURE,
  490. rejectUnauthorized: ORG_EMAIL_KEYS.EMAIL_SMTP_REJECT_UNAUTHORIZED,
  491. requireTls: ORG_EMAIL_KEYS.EMAIL_SMTP_REQUIRE_TLS,
  492. },
  493. false
  494. )
  495. case 'resend':
  496. return sendViaResendWithSettings(options, settings, ORG_EMAIL_KEYS.EMAIL_RESEND_API_KEY)
  497. case 'postmark':
  498. return sendViaPostmarkWithSettings(options, settings, ORG_EMAIL_KEYS.EMAIL_POSTMARK_API_KEY)
  499. case 'mailgun':
  500. return sendViaMailgunWithSettings(options, settings, {
  501. apiKey: ORG_EMAIL_KEYS.EMAIL_MAILGUN_API_KEY,
  502. domain: ORG_EMAIL_KEYS.EMAIL_MAILGUN_DOMAIN,
  503. region: ORG_EMAIL_KEYS.EMAIL_MAILGUN_REGION,
  504. })
  505. case 'sendgrid':
  506. return sendViaSendGridWithSettings(options, settings, ORG_EMAIL_KEYS.EMAIL_SENDGRID_API_KEY)
  507. case 'ses':
  508. return sendViaSesWithSettings(options, settings, {
  509. accessKeyId: ORG_EMAIL_KEYS.EMAIL_SES_ACCESS_KEY_ID,
  510. secretAccessKey: ORG_EMAIL_KEYS.EMAIL_SES_SECRET_ACCESS_KEY,
  511. region: ORG_EMAIL_KEYS.EMAIL_SES_REGION,
  512. })
  513. }
  514. }
  515. // system keySet
  516. switch (provider) {
  517. case 'resend':
  518. return sendViaResend(options)
  519. case 'postmark':
  520. return sendViaPostmark(options)
  521. case 'mailgun':
  522. return sendViaMailgun(options)
  523. case 'sendgrid':
  524. return sendViaSendGrid(options)
  525. case 'ses':
  526. return sendViaSes(options)
  527. default:
  528. return sendViaSmtp(options)
  529. }
  530. }
  531. // ─── System-level router (unchanged behavior) ──────────────────────────────
  532. export async function sendMail(options: SendMailOptions) {
  533. const provider = await getEmailProvider()
  534. await sendWithProvider(provider, options, new Map(), 'system')
  535. }
  536. // ─── Org-level email ────────────────────────────────────────────────────────
  537. function isEmailProvider(value: string | null | undefined): value is EmailProvider {
  538. return (
  539. value === 'smtp' ||
  540. value === 'resend' ||
  541. value === 'postmark' ||
  542. value === 'mailgun' ||
  543. value === 'sendgrid' ||
  544. value === 'ses'
  545. )
  546. }
  547. /**
  548. * The workshop's own mail vendor, from the integration it connected. An
  549. * organization that never set one up falls through to the platform's mail
  550. * settings, which is what keeps email working everywhere by default.
  551. */
  552. async function getOrgEmailProvider(organizationId: string): Promise<EmailProvider | null> {
  553. const value = await channelProvider(organizationId, 'email')
  554. return isEmailProvider(value) ? value : null
  555. }
  556. export async function getOrgFromAddress(organizationId: string): Promise<string> {
  557. const provider = await getOrgEmailProvider(organizationId)
  558. if (!provider) {
  559. return getFromAddress()
  560. }
  561. const settings = await channelSettings(organizationId, 'email')
  562. return orgFromAddressFor(provider, settings)
  563. }
  564. /**
  565. * Whether this workshop's customer mail leaves from the platform's address:
  566. * it connected no mail vendor of its own, and named none. The reply address
  567. * and the inbox email channel exist only for these workshops; a vendor of
  568. * the workshop's own sends from its own address, and replies go there.
  569. */
  570. export async function usesPlatformMail(organizationId: string): Promise<boolean> {
  571. return (await channelProvider(organizationId, 'email')) === null
  572. }
  573. /**
  574. * The platform's sending address under another name: the workshop's own,
  575. * on a mail sent for it. The address stays the platform's, since that is
  576. * the domain the mail is signed for; only the name a customer sees changes.
  577. */
  578. export async function platformFromAddressAs(displayName: string): Promise<string> {
  579. const platform = await getFromAddress()
  580. const parsed = parseMailAddress(platform)
  581. if (!parsed) return platform
  582. return formatMailAddress(displayName, parsed.email) || platform
  583. }
  584. /**
  585. * Send through one specific email connection rather than whichever the
  586. * organization is pointed at. The connection page's "send a test email" runs
  587. * through here, so the vendor being looked at is the vendor being tested,
  588. * even while a second one is still connected.
  589. */
  590. export async function sendMailThroughConnection(
  591. connectorId: string,
  592. credentials: Record<string, string>,
  593. settings: Record<string, unknown>,
  594. options: Omit<SendMailOptions, 'from'>
  595. ): Promise<{ from: string }> {
  596. const provider = messagingProvider(connectorId)
  597. if (!provider || !isEmailProvider(provider.legacyProvider)) {
  598. throw new Error(`${connectorId} is not an email integration`)
  599. }
  600. const map = asLegacyMap({
  601. connectionId: '',
  602. connectorId,
  603. provider,
  604. credentials,
  605. settings,
  606. })
  607. const from = orgFromAddressFor(provider.legacyProvider, map)
  608. await sendWithProvider(provider.legacyProvider, { ...options, from }, map, 'org')
  609. return { from }
  610. }
  611. function orgFromAddressFor(provider: EmailProvider, settings: SettingsMap): string {
  612. const keyMap: Record<EmailProvider, { email: string; name: string }> = {
  613. smtp: {
  614. email: ORG_EMAIL_KEYS.EMAIL_SMTP_FROM_EMAIL,
  615. name: ORG_EMAIL_KEYS.EMAIL_SMTP_FROM_NAME,
  616. },
  617. resend: {
  618. email: ORG_EMAIL_KEYS.EMAIL_RESEND_FROM_EMAIL,
  619. name: ORG_EMAIL_KEYS.EMAIL_RESEND_FROM_NAME,
  620. },
  621. postmark: {
  622. email: ORG_EMAIL_KEYS.EMAIL_POSTMARK_FROM_EMAIL,
  623. name: ORG_EMAIL_KEYS.EMAIL_POSTMARK_FROM_NAME,
  624. },
  625. mailgun: {
  626. email: ORG_EMAIL_KEYS.EMAIL_MAILGUN_FROM_EMAIL,
  627. name: ORG_EMAIL_KEYS.EMAIL_MAILGUN_FROM_NAME,
  628. },
  629. sendgrid: {
  630. email: ORG_EMAIL_KEYS.EMAIL_SENDGRID_FROM_EMAIL,
  631. name: ORG_EMAIL_KEYS.EMAIL_SENDGRID_FROM_NAME,
  632. },
  633. ses: {
  634. email: ORG_EMAIL_KEYS.EMAIL_SES_FROM_EMAIL,
  635. name: ORG_EMAIL_KEYS.EMAIL_SES_FROM_NAME,
  636. },
  637. }
  638. const keys = keyMap[provider]
  639. const fromEmail = settings.get(keys.email) || 'noreply@example.com'
  640. const fromName = settings.get(keys.name) || 'Torqvoice'
  641. return `${fromName} <${fromEmail}>`
  642. }
  643. export async function sendOrgMail(organizationId: string, options: SendMailOptions) {
  644. const settings = await channelSettings(organizationId, 'email')
  645. const provider = settings.get(ORG_EMAIL_KEYS.EMAIL_PROVIDER)
  646. if (!isEmailProvider(provider)) {
  647. // A workshop that named a vendor but never finished its setup used to
  648. // get that vendor's error. It still does, rather than a quiet send from
  649. // the platform's account that its customers would not recognise.
  650. const named = await legacyProviderNamed(organizationId, 'email')
  651. if (named) {
  652. throw new Error(`Email provider ${named} is not fully configured. Check its integration.`)
  653. }
  654. // Fall back to global platform email
  655. await sendMail(options)
  656. return
  657. }
  658. await sendWithProvider(provider, options, settings, 'org')
  659. }