-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontact.js
More file actions
93 lines (86 loc) · 2.76 KB
/
contact.js
File metadata and controls
93 lines (86 loc) · 2.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
const validator = require('validator');
const nodemailer = require('nodemailer');
/**
* GET /contact
* Contact form page.
*/
exports.getContact = (req, res) => {
const unknownUser = !(req.user);
res.render('contact', {
title: 'Contact',
unknownUser,
});
};
/**
* POST /contact
* Send a contact form via Nodemailer.
*/
exports.postContact = (req, res) => {
const validationErrors = [];
let fromName;
let fromEmail;
if (!req.user) {
if (validator.isEmpty(req.body.name)) validationErrors.push({ msg: 'Please enter your name' });
if (!validator.isEmail(req.body.email)) validationErrors.push({ msg: 'Please enter a valid email address.' });
}
if (validator.isEmpty(req.body.message)) validationErrors.push({ msg: 'Please enter your message.' });
if (validationErrors.length) {
req.flash('errors', validationErrors);
return res.redirect('/contact');
}
if (!req.user) {
fromName = req.body.name;
fromEmail = req.body.email;
} else {
fromName = req.user.profile.name || '';
fromEmail = req.user.email;
}
let transporter = nodemailer.createTransport({
service: 'SendGrid',
auth: {
user: process.env.SENDGRID_USER,
pass: process.env.SENDGRID_PASSWORD
}
});
const mailOptions = {
to: 'your@email.com',
from: `${fromName} <${fromEmail}>`,
subject: 'Contact Form | Hackathon Starter',
text: req.body.message
};
return transporter.sendMail(mailOptions)
.then(() => {
req.flash('success', { msg: 'Email has been sent successfully!' });
res.redirect('/contact');
})
.catch((err) => {
if (err.message === 'self signed certificate in certificate chain') {
console.log('WARNING: Self signed certificate in certificate chain. Retrying with the self signed certificate. Use a valid certificate if in production.');
transporter = nodemailer.createTransport({
service: 'SendGrid',
auth: {
user: process.env.SENDGRID_USER,
pass: process.env.SENDGRID_PASSWORD
},
tls: {
rejectUnauthorized: false
}
});
return transporter.sendMail(mailOptions);
}
console.log('ERROR: Could not send contact email after security downgrade.\n', err);
req.flash('errors', { msg: 'Error sending the message. Please try again shortly.' });
return false;
})
.then((result) => {
if (result) {
req.flash('success', { msg: 'Email has been sent successfully!' });
return res.redirect('/contact');
}
})
.catch((err) => {
console.log('ERROR: Could not send contact email.\n', err);
req.flash('errors', { msg: 'Error sending the message. Please try again shortly.' });
return res.redirect('/contact');
});
};