This repository has been archived on 2022-11-26. You can view files and clone it, but cannot push or open issues or pull requests.
IcyNet.eu/server/api/emailer.js

56 lines
1.4 KiB
JavaScript
Raw Normal View History

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-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`
export async function sendMail (address, template, context) {
2020-06-01 17:14:11 +00:00
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`
export 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
export async function init () {
2017-08-24 13:42:57 +00:00
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)
}
}