const nodemailer = require('nodemailer'); const config = require('./config'); const db = require('./database'); module.exports = { init() { if (!this.transporter) this.transporter = nodemailer.createTransport(config.smtp); }, send(options) { options.from = `${config.app.senderName} <${config.app.senderEmail}>`; if (process.env.NODE_ENV !== 'production') { if (!config.smtp.auth.user) return Promise.resolve(true); options.to = config.app.senderEmail; } let error; return this.transporter.sendMail(options).catch(err => { error = err; throw err; }).finally(async() => { await db.rawSql(` INSERT INTO vn.mail (sender, replyTo, sent, subject, body, status) VALUES (:recipient, :sender, 1, :subject, :body, :status)`, { sender: options.replyTo, recipient: options.to, subject: options.subject, body: options.text || options.html, status: error && error.message || 'Sent' }); }); } };