2017-08-24 13:42:57 +00:00
|
|
|
import {EmailTemplate} from 'email-templates'
|
|
|
|
import path from 'path'
|
|
|
|
import nodemailer from 'nodemailer'
|
2017-12-01 11:35:47 +00:00
|
|
|
|
2017-08-24 13:42:57 +00:00
|
|
|
import config from '../../scripts/load-config'
|
|
|
|
|
2017-12-07 15:37:36 +00:00
|
|
|
// TEMPORARY FIX FOR NODE v9.2.0
|
|
|
|
import tls from 'tls'
|
|
|
|
tls.DEFAULT_ECDH_CURVE = 'auto'
|
|
|
|
|
2017-08-24 13:42:57 +00:00
|
|
|
const templateDir = path.join(__dirname, '../../', 'templates')
|
|
|
|
|
|
|
|
let templateCache = {}
|
|
|
|
let transporter
|
|
|
|
|
2017-10-28 09:09:55 +00:00
|
|
|
// 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)
|
|
|
|
})
|
2017-08-24 13:42:57 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2017-10-28 09:09:55 +00:00
|
|
|
// Send an email to `email` using `template` rendered with variables from `context`
|
2017-08-24 13:42:57 +00:00
|
|
|
async function pushMail (template, email, context) {
|
2017-10-28 09:09:55 +00:00
|
|
|
if (!transporter) return null
|
2017-08-24 13:42:57 +00:00
|
|
|
let templ = null
|
|
|
|
|
|
|
|
if (!templateCache[template]) {
|
|
|
|
templ = templateCache[template] = new EmailTemplate(path.join(templateDir, template))
|
|
|
|
} else {
|
|
|
|
templ = templateCache[template]
|
|
|
|
}
|
|
|
|
|
|
|
|
let result = await templ.render(context)
|
|
|
|
|
|
|
|
console.debug('Mail being sent: %s to %s', template, email)
|
|
|
|
|
2017-10-28 09:09:55 +00:00
|
|
|
return sendMail(email, result)
|
2017-08-24 13:42:57 +00:00
|
|
|
}
|
|
|
|
|
2017-10-28 09:09:55 +00:00
|
|
|
// Transporter initialization
|
2017-08-24 13:42:57 +00:00
|
|
|
async function init () {
|
|
|
|
if (!config.email || config.email.enabled === false) return
|
|
|
|
transporter = nodemailer.createTransport(config.email.transport)
|
|
|
|
|
|
|
|
console.debug('Setting up mail transporter')
|
|
|
|
|
|
|
|
try {
|
|
|
|
await transporter.verify()
|
|
|
|
console.debug('Mail transporter initialized')
|
|
|
|
} catch (e) {
|
|
|
|
console.error('Email server verification failed')
|
|
|
|
console.error(e)
|
|
|
|
transporter = null
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
2017-10-28 09:09:55 +00:00
|
|
|
sendMail: sendMail,
|
2017-08-24 13:42:57 +00:00
|
|
|
pushMail: pushMail,
|
|
|
|
init: init
|
|
|
|
}
|