From 174e5f2a0b63ec9fc0f11f3f61f1162564235d27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20FAMIBELLE-PRONZOLA?= Date: Sat, 19 Feb 2022 21:56:23 +0400 Subject: [PATCH] Create nodemail configuration --- lib/sendmail.js | 51 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 lib/sendmail.js diff --git a/lib/sendmail.js b/lib/sendmail.js new file mode 100644 index 0000000..3448d99 --- /dev/null +++ b/lib/sendmail.js @@ -0,0 +1,51 @@ +const nodemailer = require('nodemailer') +const pick = require('lodash.pick') + +function createTransport() { + if (!process.env.SMTP_HOST && process.env.NODE_ENV === 'production') { + throw new Error('SMTP_HOST must be provided in production mode') + } + + if (process.env.SMTP_HOST) { + return nodemailer.createTransport({ + host: process.env.SMTP_HOST, + port: process.env.SMTP_PORT || 587, + secure: process.env.SMTP_SECURE === 'YES', + auth: { + user: process.env.SMTP_USERNAME, + pass: process.env.SMTP_PASSWORD + } + }) + } + + return nodemailer.createTransport({ + streamTransport: true, + newline: 'unix', + buffer: true + }) +} + +const transport = createTransport() + +async function sendMail(email, recipients = []) { + if (recipients.length === 0) { + throw new Error('At least one recipient must be provided') + } + + const info = await transport.sendMail({ + ...pick(email, 'text', 'html', 'subject'), + from: process.env.SMTP_FROM, + to: recipients, + bcc: process.env.SMTP_BCC ? process.env.SMTP_BCC.split(',') : undefined + }) + + if (process.env.SHOW_EMAILS === 'YES' && transport.transporter.options.streamTransport) { + console.log('-----------------------') + console.log(info.message.toString()) + console.log('-----------------------') + } + + return info +} + +module.exports = {sendMail, createTransport, transport}