contact.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. const nodemailer = require('nodemailer');
  2. const transporter = nodemailer.createTransport({
  3. service: 'SendGrid',
  4. auth: {
  5. user: process.env.SENDGRID_USER,
  6. pass: process.env.SENDGRID_PASSWORD
  7. }
  8. });
  9. /**
  10. * GET /contact
  11. * Contact form page.
  12. */
  13. exports.getContact = (req, res) => {
  14. const unknownUser = !(req.user);
  15. res.render('contact', {
  16. title: 'Contact',
  17. unknownUser,
  18. });
  19. };
  20. /**
  21. * POST /contact
  22. * Send a contact form via Nodemailer.
  23. */
  24. exports.postContact = (req, res) => {
  25. let fromName;
  26. let fromEmail;
  27. if (!req.user) {
  28. req.assert('name', 'Name cannot be blank').notEmpty();
  29. req.assert('email', 'Email is not valid').isEmail();
  30. }
  31. req.assert('message', 'Message cannot be blank').notEmpty();
  32. const errors = req.validationErrors();
  33. if (errors) {
  34. req.flash('errors', errors);
  35. return res.redirect('/contact');
  36. }
  37. if (!req.user) {
  38. fromName = req.body.name;
  39. fromEmail = req.body.email;
  40. } else {
  41. fromName = req.user.profile.name || '';
  42. fromEmail = req.user.email;
  43. }
  44. const mailOptions = {
  45. to: 'your@email.com',
  46. from: `${fromName} <${fromEmail}>`,
  47. subject: 'Contact Form | Hackathon Starter',
  48. text: req.body.message
  49. };
  50. transporter.sendMail(mailOptions, (err) => {
  51. if (err) {
  52. req.flash('errors', { msg: err.message });
  53. return res.redirect('/contact');
  54. }
  55. req.flash('success', { msg: 'Email has been sent successfully!' });
  56. res.redirect('/contact');
  57. });
  58. };