forked from nodejsapps/TypeScript-Node-Starter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontact.ts
More file actions
54 lines (47 loc) · 1.48 KB
/
Copy pathcontact.ts
File metadata and controls
54 lines (47 loc) · 1.48 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
import nodemailer from "nodemailer";
import { Request, Response } from "express";
import { check, validationResult } from "express-validator";
const transporter = nodemailer.createTransport({
service: "SendGrid",
auth: {
user: process.env.SENDGRID_USER,
pass: process.env.SENDGRID_PASSWORD
}
});
/**
* Contact form page.
* @route GET /contact
*/
export const getContact = (req: Request, res: Response) => {
res.render("contact", {
title: "Contact"
});
};
/**
* Send a contact form via Nodemailer.
* @route POST /contact
*/
export const postContact = async (req: Request, res: Response) => {
await check("name", "Name cannot be blank").not().isEmpty().run(req);
await check("email", "Email is not valid").isEmail().run(req);
await check("message", "Message cannot be blank").not().isEmpty().run(req);
const errors = validationResult(req);
if (!errors.isEmpty()) {
req.flash("errors", errors.array());
return res.redirect("/contact");
}
const mailOptions = {
to: "your@email.com",
from: `${req.body.name} <${req.body.email}>`,
subject: "Contact Form",
text: req.body.message
};
transporter.sendMail(mailOptions, (err) => {
if (err) {
req.flash("errors", { msg: err.message });
return res.redirect("/contact");
}
req.flash("success", { msg: "Email has been sent successfully!" });
res.redirect("/contact");
});
};