2020-06-01 17:14:11 +00:00
|
|
|
import Email from 'email-templates'
|
2017-08-24 13:42:57 +00:00
|
|
|
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'
|
|
|
|
|
|
|
|
const templateDir = path.join(__dirname, '../../', 'templates')
|
2020-06-01 17:14:11 +00:00
|
|
|
const email = new Email({
|
|
|
|
message: {
|
|
|
|
from: config.email.admin
|
|
|
|
},
|
|
|
|
views: {
|
|
|
|
root: path.resolve(templateDir)
|
|
|
|
},
|
|
|
|
send: true
|
|
|
|
})
|
2017-08-24 13:42:57 +00:00
|
|
|
|
2017-10-28 09:09:55 +00:00
|
|
|
// Send an email to `email` with `headers`
|
2020-06-01 17:14:11 +00:00
|
|
|
async function sendMail (address, template, context) {
|
|
|
|
if (!email.transport) throw new Error('No transporter present!')
|
|
|
|
|
|
|
|
return email.send({
|
|
|
|
template,
|
|
|
|
locals: context,
|
|
|
|
message: {
|
|
|
|
to: address
|
|
|
|
}
|
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`
|
2020-06-01 17:14:11 +00:00
|
|
|
async function pushMail (template, address, context) {
|
2017-08-24 13:42:57 +00:00
|
|
|
console.debug('Mail being sent: %s to %s', template, email)
|
|
|
|
|
2020-06-01 17:14:11 +00:00
|
|
|
return sendMail(address, template, context)
|
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
|
2020-06-01 17:14:11 +00:00
|
|
|
const transporter = nodemailer.createTransport(config.email.transport)
|
2017-08-24 13:42:57 +00:00
|
|
|
|
|
|
|
console.debug('Setting up mail transporter')
|
|
|
|
|
|
|
|
try {
|
|
|
|
await transporter.verify()
|
2020-06-01 17:14:11 +00:00
|
|
|
email.config.transport = transporter
|
|
|
|
email.transport = transporter
|
2017-08-24 13:42:57 +00:00
|
|
|
console.debug('Mail transporter initialized')
|
|
|
|
} catch (e) {
|
|
|
|
console.error('Email server verification failed')
|
|
|
|
console.error(e)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
2017-10-28 09:09:55 +00:00
|
|
|
sendMail: sendMail,
|
2017-08-24 13:42:57 +00:00
|
|
|
pushMail: pushMail,
|
|
|
|
init: init
|
|
|
|
}
|