Skip to content

Instantly share code, notes, and snippets.

@npfitz
Created February 18, 2015 18:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save npfitz/fd641c9366b1db40ef4e to your computer and use it in GitHub Desktop.
Save npfitz/fd641c9366b1db40ef4e to your computer and use it in GitHub Desktop.
var mandrill = require('mandrill-api/mandrill'),
async = require('async'),
User = require('../../models').User;
module.exports = function (apiKey, lang) {
// setup mandrill api
var mandrill_client = new mandrill.Mandrill(apiKey);
function sendEmail (user_id, entry_id) {
async.waterfall([
function (callback) {
// Find user record based on provided user id
User.findById(user_id, function (err, user) {
console.log('--- Email: findUser - user_id:' + user_id);
callback(err, user);
});
},
function (user, callback) {
// if no user is found then return error
if (!user) return callback(new Error('no user found!'), null);
var templateName = lang == 'fr' ?
'sunlight-winner-confirmation-fr' :
'sunlight-winner-confirmation';
// get html email template
mandrill_client.templates.info({'name': templateName}, function (template) {
console.log('--- Email: findEmailTemplate: sunlight-winner-confirmation', templateName, lang);
callback(null, user, template);
}, function(err) {
// Mandrill returns the error as an object with name and message keys
callback(err, null);
});
},
function (user, template, callback) {
// FINALLY send this mofo email!!
var message = getEmailMessage(user, entry_id, template);
mandrill_client.messages.send({"message": message, "async": false}, function (result) {
console.log('--- Email: SendEmail: - result: ', result);
callback(null, result);
}, function(e) {
// Mandrill returns the error as an object with name and message keys
callback(err, null);
});
}
], function (err, result) {
if (err) {
console.log('--- Email: - Error: ', err);
return false;
}
return result;
});
};
function getEmailMessage (user, entry_id, template) {
// assemble message object
// see https://mandrillapp.com/api/docs/messages.nodejs.html
var message = {
"html": template.code,
"text": template.text,
"subject": template.subject,
"from_email": template.from_email,
"from_name": template.from_name,
"to": [{
"email": user.decrypt.email,
"name": user.fullname,
"type": "to"
}],
"important": false,
"track_opens": true,
"track_clicks": null,
"inline_css": true,
"tracking_domain": null,
"signing_domain": null,
"return_path_domain": null,
"recipient_metadata": null,
"images": null,
"recipient_metadata": [{
"rcpt": user.decrypt.email,
"values": {
"user_id": user.id,
"name": user.fullname,
"entry_id": entry_id
}
}],
};
return message;
};
return {
sendEmail: sendEmail
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment