change emailer

This commit is contained in:
Evert Prants 2017-10-28 12:09:55 +03:00
parent 57909b8130
commit cf6622763a
Signed by: evert
GPG Key ID: 1688DA83D222D0B5
2 changed files with 33 additions and 20 deletions

View File

@ -8,24 +8,27 @@ const templateDir = path.join(__dirname, '../../', 'templates')
let templateCache = {} let templateCache = {}
let transporter let transporter
function sendMail (email, headers) { // Send an email to `email` with `headers`
if (!transporter) return async function sendMail (email, headers) {
transporter.sendMail({ return new Promise(function (resolve, reject) {
from: config.email.admin, if (!transporter) return reject(new Error('No transporter present!'))
to: email,
subject: headers.subject, transporter.sendMail(Object.assign({
html: headers.html, from: config.email.admin,
text: headers.text to: email
}, (error, info) => { }, headers), (error, info) => {
if (error) { if (error) {
return console.error(error) return reject(error)
} }
console.debug(info)
resolve(info)
})
}) })
} }
// Send an email to `email` using `template` rendered with variables from `context`
async function pushMail (template, email, context) { async function pushMail (template, email, context) {
if (!transporter) return if (!transporter) return null
let templ = null let templ = null
if (!templateCache[template]) { if (!templateCache[template]) {
@ -38,9 +41,10 @@ async function pushMail (template, email, context) {
console.debug('Mail being sent: %s to %s', template, email) console.debug('Mail being sent: %s to %s', template, email)
sendMail(email, result) return sendMail(email, result)
} }
// Transporter initialization
async function init () { async function init () {
if (!config.email || config.email.enabled === false) return if (!config.email || config.email.enabled === false) return
transporter = nodemailer.createTransport(config.email.transport) transporter = nodemailer.createTransport(config.email.transport)
@ -58,6 +62,7 @@ async function init () {
} }
module.exports = { module.exports = {
sendMail: sendMail,
pushMail: pushMail, pushMail: pushMail,
init: init init: init
} }

View File

@ -380,11 +380,19 @@ const API = {
// Send Activation Email // Send Activation Email
console.debug('Activation token:', activationToken) console.debug('Activation token:', activationToken)
if (email) { if (email) {
await emailer.pushMail('activate', user.email, { try {
domain: config.server.domain, let em = await emailer.pushMail('activate', user.email, {
display_name: user.display_name, domain: config.server.domain,
activation_token: activationToken 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} return {error: null, user: user}