Last active
May 24, 2016 16:02
-
-
Save KieronWiltshire/a86ad6e9ba7c084f80eb855604d92e39 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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': '[email protected]' | |
}, | |
'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