Skip to content

Instantly share code, notes, and snippets.

@eyy
Last active December 20, 2015 04:39
Show Gist options
  • Save eyy/6072677 to your computer and use it in GitHub Desktop.
Save eyy/6072677 to your computer and use it in GitHub Desktop.
send mail with express and sendgrid
/**package
{
"name": "mailson",
"description": "Mailing for kids",
"version": "0.1.0",
"author": {
"name": "Etay Perez",
"email": "[email protected]"
},
"dependencies": {
"nodemailer" : ""
},
"license": "MIT"
}
**/
var nodemailer = require('nodemailer'),
mail,
options;
var send = module.exports = function(req, res) {
if (!mail) {
console.error('please init() mail first');
return res.send(500);
}
var message = {
from: req.body.email,
to: options.email,
subject: options.subject + ' mail from ' + req.body.name,
text: send.template(req.body)
};
mail.sendMail(message, function(err, response) {
if (err)
console.error('Error: Could not send mail.', response, err, message);
else
console.log('A mail was sent from', req.body.email);
res.json(err ? 502 : 201, { success: !err });
});
};
send.template = function(o) {
return Object.keys(o).map(function(k) {
return k + ': ' + o[k];
}).join('\n');
};
send.init = function(sg, o) {
if (!sg.user || !sg.key)
return console.error('mail.js: where is sendgrid config?', sg);
options = o;
o.template && (send.template = o.template);
mail = nodemailer.createTransport('SMTP', {
service: "SendGrid",
auth: {
user: sg.user,
pass: sg.key
}
});
};
/*
Package.json:
"mailson": "https://gist.github.com/eyy/6072677/raw/mail.js"
Backend:
var mail = require('mailson');
mail.init(app.get('sendgrid'), {
subject: app.get('site'),
email: '[email protected]'
});
app.post('/mail', mail);
Frontend:
$('form#mail').submit(function(e) {
e.preventDefault();
var form = $(this);
$('[type=submit]', form).prop('disable', true).attr('value', 'Sending...');
$.post(form.attr('action'), form.serialize(), function(res) {
form.hide();
$('#sent').removeClass('hide');
});
});
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment