freeCodeCamp/controllers/contact.js

60 lines
1.4 KiB
JavaScript
Raw Normal View History

var secrets = require('../config/secrets');
var sendgrid = require('sendgrid')(secrets.sendgrid.user, secrets.sendgrid.password);
/**
* GET /contact
2014-01-07 23:15:14 +00:00
* Contact form page.
*/
2014-01-13 09:34:54 +00:00
exports.getContact = function(req, res) {
2013-11-20 04:19:53 +00:00
res.render('contact', {
title: 'Contact',
success: req.flash('success'),
errors: req.flash('errors')
2013-11-20 04:19:53 +00:00
});
};
/**
* POST /contact
* Send a contact form via SendGrid.
* @param {string} email
* @param {string} name
* @param {string} message
*/
exports.postContact = function(req, res) {
req.assert('name', 'Name cannot be blank').notEmpty();
req.assert('email', 'Email cannot be blank').notEmpty();
req.assert('email', 'Email is not valid').isEmail();
req.assert('message', 'Message cannot be blank').notEmpty();
var errors = req.validationErrors();
if (errors) {
req.flash('errors', errors);
return res.redirect('/contact');
}
var from = req.body.email;
2013-12-05 01:55:01 +00:00
var name = req.body.name;
var body = req.body.message;
2014-01-24 03:25:13 +00:00
var to = 'you@email.com';
var subject = 'API Example | Contact Form';
var email = new sendgrid.Email({
2014-01-13 09:34:54 +00:00
to: to,
from: from,
subject: subject,
text: body + '\n\n' + name
});
sendgrid.send(email, function(err) {
if (err) {
req.flash('errors', { msg: err.message });
return res.redirect('/contact');
}
req.flash('success', 'Email has been sent successfully!');
res.redirect('/contact');
});
};