Fix the mailer
This commit is contained in:
parent
787cc6fc73
commit
2a7aec1b46
@ -1,68 +1,55 @@
|
||||
import { EmailTemplate } from 'email-templates'
|
||||
import Email 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')
|
||||
|
||||
const templateCache = {}
|
||||
let transporter
|
||||
const email = new Email({
|
||||
message: {
|
||||
from: config.email.admin
|
||||
},
|
||||
views: {
|
||||
root: path.resolve(templateDir)
|
||||
},
|
||||
send: true
|
||||
})
|
||||
|
||||
// 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!'))
|
||||
async function sendMail (address, template, context) {
|
||||
if (!email.transport) throw 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)
|
||||
})
|
||||
return email.send({
|
||||
template,
|
||||
locals: context,
|
||||
message: {
|
||||
to: address
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 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]
|
||||
}
|
||||
|
||||
const result = await templ.render(context)
|
||||
|
||||
async function pushMail (template, address, context) {
|
||||
console.debug('Mail being sent: %s to %s', template, email)
|
||||
|
||||
return sendMail(email, result)
|
||||
return sendMail(address, template, context)
|
||||
}
|
||||
|
||||
// Transporter initialization
|
||||
async function init () {
|
||||
if (!config.email || config.email.enabled === false) return
|
||||
transporter = nodemailer.createTransport(config.email.transport)
|
||||
const transporter = nodemailer.createTransport(config.email.transport)
|
||||
|
||||
console.debug('Setting up mail transporter')
|
||||
|
||||
try {
|
||||
await transporter.verify()
|
||||
email.config.transport = transporter
|
||||
email.transport = transporter
|
||||
console.debug('Mail transporter initialized')
|
||||
} catch (e) {
|
||||
console.error('Email server verification failed')
|
||||
console.error(e)
|
||||
transporter = null
|
||||
}
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user