From 2a7aec1b46ced51478e1783aa7916bf4bb38dd31 Mon Sep 17 00:00:00 2001 From: Evert Prants Date: Mon, 1 Jun 2020 20:14:11 +0300 Subject: [PATCH] Fix the mailer --- server/api/emailer.js | 59 +++++++++++++++++-------------------------- 1 file changed, 23 insertions(+), 36 deletions(-) diff --git a/server/api/emailer.js b/server/api/emailer.js index c628468..2abb1c7 100644 --- a/server/api/emailer.js +++ b/server/api/emailer.js @@ -1,68 +1,55 @@ -import { EmailTemplate } from 'email-templates' +import Email from 'email-templates' import path from 'path' import nodemailer from 'nodemailer' import config from '../../scripts/load-config' -// TEMPORARY FIX FOR NODE v9.2.0 -import tls from 'tls' -tls.DEFAULT_ECDH_CURVE = 'auto' - const templateDir = path.join(__dirname, '../../', 'templates') - -const templateCache = {} -let transporter +const email = new Email({ + message: { + from: config.email.admin + }, + views: { + root: path.resolve(templateDir) + }, + send: true +}) // Send an email to `email` with `headers` -async function sendMail (email, headers) { - return new Promise(function (resolve, reject) { - if (!transporter) return reject(new Error('No transporter present!')) +async function sendMail (address, template, context) { + if (!email.transport) throw new Error('No transporter present!') - transporter.sendMail(Object.assign({ - from: config.email.admin, - to: email - }, headers), (error, info) => { - if (error) { - return reject(error) - } - - resolve(info) - }) + return email.send({ + template, + locals: context, + message: { + to: address + } }) } // Send an email to `email` using `template` rendered with variables from `context` -async function pushMail (template, email, context) { - if (!transporter) return null - let templ = null - - if (!templateCache[template]) { - templ = templateCache[template] = new EmailTemplate(path.join(templateDir, template)) - } else { - templ = templateCache[template] - } - - const result = await templ.render(context) - +async function pushMail (template, address, context) { console.debug('Mail being sent: %s to %s', template, email) - return sendMail(email, result) + return sendMail(address, template, context) } // Transporter initialization async function init () { if (!config.email || config.email.enabled === false) return - transporter = nodemailer.createTransport(config.email.transport) + const transporter = nodemailer.createTransport(config.email.transport) console.debug('Setting up mail transporter') try { await transporter.verify() + email.config.transport = transporter + email.transport = transporter console.debug('Mail transporter initialized') } catch (e) { console.error('Email server verification failed') console.error(e) - transporter = null } }