| 1 | import { createLogger } from 'evlog' |
| 2 | import type { Transporter |
| 3 | import nodemailer from 'nodemailer |
| 4 | import type SMTPTransport from |
| 5 | import { env } |
| 6 | |
| 7 | const log = createLogger |
| 8 | |
| 9 | interface SendEmailParams { |
| 10 | from?: string |
| 11 | html: string |
| 12 | replyTo?: string |
| 13 | subject: string |
| 14 | text?: string |
| 15 | to: string |
| 16 | } |
| 17 | |
| 18 | class EmailService { |
| 19 | private readonly transporter |
| 20 | private readonly defaultSender |
| 21 | private readonly proxyUrl |
| 22 | private readonly proxySecret |
| 23 | |
| 24 | constructor() { |
| 25 | this.proxyUrl = |
| 26 | this.proxySecret = |
| 27 | |
| 28 | if (this.proxyUrl |
| 29 | this.transporter = |
| 30 | log.info('Using email proxy |
| 31 | } else { |
| 32 | this.transporter = |
| 33 | host: env.MAIL_HOST |
| 34 | port: env.MAIL_PORT |
| 35 | secure: env.MAIL_SECURE |
| 36 | auth: { |
| 37 | user: env.MAIL_USER |
| 38 | pass: env.MAIL_PASSWORD |
| 39 | }, |
| 40 | } as SMTPTransport. |
| 41 | } |
| 42 | |
| 43 | this.defaultSender = |
| 44 | ? `Saturn <${env. |
| 45 | : 'Saturn <noreply@saturn.procrastinator.fyi>' |
| 46 | } |
| 47 | |
| 48 | async sendEmail({ |
| 49 | to, |
| 50 | subject, |
| 51 | html, |
| 52 | from, |
| 53 | replyTo, |
| 54 | text, |
| 55 | }: SendEmailParams |
| 56 | const sender = |
| 57 | |
| 58 | if (this.proxyUrl |
| 59 | return this.sendViaProxy |
| 60 | } |
| 61 | |
| 62 | const mailOptions: |
| 63 | from: sender, |
| 64 | to, |
| 65 | subject, |
| 66 | html, |
| 67 | replyTo: replyTo || |
| 68 | text, |
| 69 | } |
| 70 | |
| 71 | try { |
| 72 | const res = |
| 73 | log.info('Email sent |
| 74 | } catch (error) |
| 75 | log.error('Failed to send email |
| 76 | throw new Error( |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | private async sendViaProxy |
| 81 | to, |
| 82 | subject, |
| 83 | html, |
| 84 | from, |
| 85 | text, |
| 86 | }: { |
| 87 | to: string |
| 88 | subject: string |
| 89 | html: string |
| 90 | from: string |
| 91 | text?: string |
| 92 | }): Promise |
| 93 | try { |
| 94 | const res = |
| 95 | method: 'POST', |
| 96 | headers: { 'Content-Type': |
| 97 | body: JSON.stringify |
| 98 | to, |
| 99 | subject, |
| 100 | htmlBody: html, |
| 101 | textBody: text, |
| 102 | from, |
| 103 | secret: this.proxySecret |
| 104 | }), |
| 105 | }) |
| 106 | |
| 107 | if (!res.ok |
| 108 | const body = |
| 109 | throw new Error( |
| 110 | } |
| 111 | |
| 112 | log.info('Email sent via proxy |
| 113 | } catch (error) |
| 114 | log.error('Failed to send email via proxy |
| 115 | throw new Error( |
| 116 | } |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | export const emailService = |