Skip to content

Instantly share code, notes, and snippets.

@KieronWiltshire
Last active May 24, 2016 16:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KieronWiltshire/a86ad6e9ba7c084f80eb855604d92e39 to your computer and use it in GitHub Desktop.
Save KieronWiltshire/a86ad6e9ba7c084f80eb855604d92e39 to your computer and use it in GitHub Desktop.
'use strict';
var path = require('path');
var config = require('./config');
var debug = require('debug')('web:mailer');
var nodemailer = require('nodemailer');
var smtp = require('nodemailer-smtp-transport');
var _ = require('lodash');
var fs = require('fs');
var errors = require('./errors');
/**
* Mailer
* --------------------------------------------------
*/
var options = config.has('email') ? config.get('email') : null;
var transport = nodemailer.createTransport(smtp(options));
var templater = config.has('app.view-engine') ? config.get('app.view-engine') : 'pug';
var templateEngine = require(templater);
var mailer = function(template, options) {
return new Promise(function(resolve, reject) {
var templateLocation = template.split('.');
template = path.join(__dirname, 'views');
for (var index in templateLocation) {
template = path.join(template, templateLocation[index]);
}
if (fs.statSync(template + '.' + templater)) {
var html = templateEngine.renderFile(template + '.' + templater, options.context);
options = _.extend(options, {
'from': config.has('email.from') ? config.get('email.from') : {
'name': 'Dracade',
'address': 'no.reply@dracade.com'
},
'html': html
});
transport.sendMail(options, function(error, response) {
if (error) {
debug(error);
reject(new errors.InternalServerError(i18n.__('errors.unableToSendEmail')));
} else {
resolve();
}
});
} else {
reject(new errors.InternalServerError(i18n.__('errors.templateNotFound')));
}
});
};
module.exports = mailer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment