salix/services/mailer/application/mail.js

70 lines
2.1 KiB
JavaScript

var nodemailer = require('nodemailer');
var settings = require('./settings.js');
var template = require('./template.js');
/**
* Mail module
*/
module.exports = {
transporter: null,
/**
* Load mail settings.
*/
init: function() {
this.transporter = nodemailer.createTransport(settings.smtp());
this.transporter.verify(function(error, success) {
if (error) {
throw new Error(error);
} else if (settings.app().debug) {
console.log('SMTP connection stablished');
}
});
},
/**
* Send email.
* @param {Object} recipient - Mail destinatary
* @param {String} subject - Subject
* @param {String} body - Mail body
* @param {Object} attachments - Mail attachments
* @param {Object} cb - Callback
*/
send: function(recipient, subject, body, attachments, cb) {
let mailOptions = {
from: '"' + settings.app().senderName + '" <' + settings.app().senderMail + '>',
to: recipient,
subject: subject,
html: body,
attachments
};
if (process.env.NODE_ENV !== 'production') {
mailOptions.to = settings.testEmail;
}
this.transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return cb({status: 'REJECT', data: {message: 'Email not sent: ' + error}});
} else if (settings.app().debug) {
console.log('Mail sent ' + info.messageId + ' [' + info.response + ']');
}
cb({status: 'ACCEPT', data: {message: 'Email sent'}});
});
},
/**
* Send email with template.
* @param {String} tplName - Template name
* @param {Object} params - Params object
* @param {Object} cb - Callback
*/
sendWithTemplate: function(tplName, params, cb) {
template.get(tplName, params, data => {
this.send(data.recipient, data.subject, data.body, data.attachments, result => {
cb(result);
});
});
}
};