From cf6622763a119182643b781fc96f07ca5e85b079 Mon Sep 17 00:00:00 2001 From: Evert Date: Sat, 28 Oct 2017 12:09:55 +0300 Subject: [PATCH] change emailer --- server/api/emailer.js | 35 ++++++++++++++++++++--------------- server/api/index.js | 18 +++++++++++++----- 2 files changed, 33 insertions(+), 20 deletions(-) diff --git a/server/api/emailer.js b/server/api/emailer.js index 800e0a0..1779a1b 100644 --- a/server/api/emailer.js +++ b/server/api/emailer.js @@ -8,24 +8,27 @@ const templateDir = path.join(__dirname, '../../', 'templates') let templateCache = {} let transporter -function sendMail (email, headers) { - if (!transporter) return - transporter.sendMail({ - from: config.email.admin, - to: email, - subject: headers.subject, - html: headers.html, - text: headers.text - }, (error, info) => { - if (error) { - return console.error(error) - } - console.debug(info) +// 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!')) + + transporter.sendMail(Object.assign({ + from: config.email.admin, + to: email + }, headers), (error, info) => { + if (error) { + return reject(error) + } + + resolve(info) + }) }) } +// Send an email to `email` using `template` rendered with variables from `context` async function pushMail (template, email, context) { - if (!transporter) return + if (!transporter) return null let templ = null if (!templateCache[template]) { @@ -38,9 +41,10 @@ async function pushMail (template, email, context) { console.debug('Mail being sent: %s to %s', template, email) - sendMail(email, result) + return sendMail(email, result) } +// Transporter initialization async function init () { if (!config.email || config.email.enabled === false) return transporter = nodemailer.createTransport(config.email.transport) @@ -58,6 +62,7 @@ async function init () { } module.exports = { + sendMail: sendMail, pushMail: pushMail, init: init } diff --git a/server/api/index.js b/server/api/index.js index 312b169..8ee6276 100644 --- a/server/api/index.js +++ b/server/api/index.js @@ -380,11 +380,19 @@ const API = { // Send Activation Email console.debug('Activation token:', activationToken) if (email) { - await emailer.pushMail('activate', user.email, { - domain: config.server.domain, - display_name: user.display_name, - activation_token: activationToken - }) + try { + let em = await emailer.pushMail('activate', user.email, { + domain: config.server.domain, + display_name: user.display_name, + activation_token: activationToken + }) + + console.debug(em) + } catch (e) { + console.error(e) + await models.User.query().delete().where('id', user.id) + return {error: 'Invalid email address!'} + } } return {error: null, user: user}