74 lines
1.8 KiB
JavaScript
74 lines
1.8 KiB
JavaScript
import {EmailTemplate} 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')
|
|
|
|
let templateCache = {}
|
|
let transporter
|
|
|
|
// 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 null
|
|
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)
|
|
|
|
return sendMail(email, result)
|
|
}
|
|
|
|
// Transporter initialization
|
|
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 = {
|
|
sendMail: sendMail,
|
|
pushMail: pushMail,
|
|
init: init
|
|
}
|