|
1 | 1 | const fs = require('fs');
|
2 | 2 | const path = require('path');
|
| 3 | +const axios = require('axios'); |
| 4 | +const FormData = require('form-data'); |
3 | 5 | const nodemailer = require('nodemailer');
|
4 | 6 | const handlebars = require('handlebars');
|
5 | 7 | const { isEnabled } = require('~/server/utils/handleText');
|
| 8 | +const { logAxiosError } = require('~/utils'); |
6 | 9 | const logger = require('~/config/winston');
|
7 | 10 |
|
| 11 | +/** |
| 12 | + * Sends an email using Mailgun API. |
| 13 | + * |
| 14 | + * @async |
| 15 | + * @function sendEmailViaMailgun |
| 16 | + * @param {Object} params - The parameters for sending the email. |
| 17 | + * @param {string} params.to - The recipient's email address. |
| 18 | + * @param {string} params.from - The sender's email address. |
| 19 | + * @param {string} params.subject - The subject of the email. |
| 20 | + * @param {string} params.html - The HTML content of the email. |
| 21 | + * @returns {Promise<Object>} - A promise that resolves to the response from Mailgun API. |
| 22 | + */ |
| 23 | +const sendEmailViaMailgun = async ({ to, from, subject, html }) => { |
| 24 | + const mailgunApiKey = process.env.MAILGUN_API_KEY; |
| 25 | + const mailgunDomain = process.env.MAILGUN_DOMAIN; |
| 26 | + const mailgunHost = process.env.MAILGUN_HOST || 'https://api.mailgun.net'; |
| 27 | + |
| 28 | + if (!mailgunApiKey || !mailgunDomain) { |
| 29 | + throw new Error('Mailgun API key and domain are required'); |
| 30 | + } |
| 31 | + |
| 32 | + const formData = new FormData(); |
| 33 | + formData.append('from', from); |
| 34 | + formData.append('to', to); |
| 35 | + formData.append('subject', subject); |
| 36 | + formData.append('html', html); |
| 37 | + |
| 38 | + try { |
| 39 | + const response = await axios.post(`${mailgunHost}/v3/${mailgunDomain}/messages`, formData, { |
| 40 | + headers: { |
| 41 | + ...formData.getHeaders(), |
| 42 | + Authorization: `Basic ${Buffer.from(`api:${mailgunApiKey}`).toString('base64')}`, |
| 43 | + }, |
| 44 | + }); |
| 45 | + |
| 46 | + return response.data; |
| 47 | + } catch (error) { |
| 48 | + throw new Error(logAxiosError({ error, message: 'Failed to send email via Mailgun' })); |
| 49 | + } |
| 50 | +}; |
| 51 | + |
| 52 | +/** |
| 53 | + * Sends an email using SMTP via Nodemailer. |
| 54 | + * |
| 55 | + * @async |
| 56 | + * @function sendEmailViaSMTP |
| 57 | + * @param {Object} params - The parameters for sending the email. |
| 58 | + * @param {Object} params.transporterOptions - The transporter configuration options. |
| 59 | + * @param {Object} params.mailOptions - The email options. |
| 60 | + * @returns {Promise<Object>} - A promise that resolves to the info object of the sent email. |
| 61 | + */ |
| 62 | +const sendEmailViaSMTP = async ({ transporterOptions, mailOptions }) => { |
| 63 | + const transporter = nodemailer.createTransport(transporterOptions); |
| 64 | + return await transporter.sendMail(mailOptions); |
| 65 | +}; |
| 66 | + |
8 | 67 | /**
|
9 | 68 | * Sends an email using the specified template, subject, and payload.
|
10 | 69 | *
|
@@ -34,6 +93,30 @@ const logger = require('~/config/winston');
|
34 | 93 | */
|
35 | 94 | const sendEmail = async ({ email, subject, payload, template, throwError = true }) => {
|
36 | 95 | try {
|
| 96 | + // Read and compile the email template |
| 97 | + const source = fs.readFileSync(path.join(__dirname, 'emails', template), 'utf8'); |
| 98 | + const compiledTemplate = handlebars.compile(source); |
| 99 | + const html = compiledTemplate(payload); |
| 100 | + |
| 101 | + // Prepare common email data |
| 102 | + const fromName = process.env.EMAIL_FROM_NAME || process.env.APP_TITLE; |
| 103 | + const fromEmail = process.env.EMAIL_FROM; |
| 104 | + const fromAddress = `"${fromName}" <${fromEmail}>`; |
| 105 | + const toAddress = `"${payload.name}" <${email}>`; |
| 106 | + |
| 107 | + // Check if Mailgun is configured |
| 108 | + if (process.env.MAILGUN_API_KEY && process.env.MAILGUN_DOMAIN) { |
| 109 | + logger.debug('[sendEmail] Using Mailgun provider'); |
| 110 | + return await sendEmailViaMailgun({ |
| 111 | + from: fromAddress, |
| 112 | + to: toAddress, |
| 113 | + subject: subject, |
| 114 | + html: html, |
| 115 | + }); |
| 116 | + } |
| 117 | + |
| 118 | + // Default to SMTP |
| 119 | + logger.debug('[sendEmail] Using SMTP provider'); |
37 | 120 | const transporterOptions = {
|
38 | 121 | // Use STARTTLS by default instead of obligatory TLS
|
39 | 122 | secure: process.env.EMAIL_ENCRYPTION === 'tls',
|
@@ -62,30 +145,21 @@ const sendEmail = async ({ email, subject, payload, template, throwError = true
|
62 | 145 | transporterOptions.port = process.env.EMAIL_PORT ?? 25;
|
63 | 146 | }
|
64 | 147 |
|
65 |
| - const transporter = nodemailer.createTransport(transporterOptions); |
66 |
| - |
67 |
| - const source = fs.readFileSync(path.join(__dirname, 'emails', template), 'utf8'); |
68 |
| - const compiledTemplate = handlebars.compile(source); |
69 |
| - const options = () => { |
70 |
| - return { |
71 |
| - // Header address should contain name-addr |
72 |
| - from: |
73 |
| - `"${process.env.EMAIL_FROM_NAME || process.env.APP_TITLE}"` + |
74 |
| - `<${process.env.EMAIL_FROM}>`, |
75 |
| - to: `"${payload.name}" <${email}>`, |
76 |
| - envelope: { |
77 |
| - // Envelope from should contain addr-spec |
78 |
| - // Mistake in the Nodemailer documentation? |
79 |
| - from: process.env.EMAIL_FROM, |
80 |
| - to: email, |
81 |
| - }, |
82 |
| - subject: subject, |
83 |
| - html: compiledTemplate(payload), |
84 |
| - }; |
| 148 | + const mailOptions = { |
| 149 | + // Header address should contain name-addr |
| 150 | + from: fromAddress, |
| 151 | + to: toAddress, |
| 152 | + envelope: { |
| 153 | + // Envelope from should contain addr-spec |
| 154 | + // Mistake in the Nodemailer documentation? |
| 155 | + from: fromEmail, |
| 156 | + to: email, |
| 157 | + }, |
| 158 | + subject: subject, |
| 159 | + html: html, |
85 | 160 | };
|
86 | 161 |
|
87 |
| - // Send email |
88 |
| - return await transporter.sendMail(options()); |
| 162 | + return await sendEmailViaSMTP({ transporterOptions, mailOptions }); |
89 | 163 | } catch (error) {
|
90 | 164 | if (throwError) {
|
91 | 165 | throw error;
|
|
0 commit comments