mirror of
https://github.com/microsoft/TypeScript-Node-Starter.git
synced 2025-11-09 20:37:26 +00:00
54 lines
1.2 KiB
TypeScript
54 lines
1.2 KiB
TypeScript
import nodemailer from "nodemailer";
|
|
import { Request, Response } from "express";
|
|
|
|
const transporter = nodemailer.createTransport({
|
|
service: "SendGrid",
|
|
auth: {
|
|
user: process.env.SENDGRID_USER,
|
|
pass: process.env.SENDGRID_PASSWORD
|
|
}
|
|
});
|
|
|
|
/**
|
|
* GET /contact
|
|
* Contact form page.
|
|
*/
|
|
export const getContact = (req: Request, res: Response) => {
|
|
res.render("contact", {
|
|
title: "Contact"
|
|
});
|
|
};
|
|
|
|
/**
|
|
* POST /contact
|
|
* Send a contact form via Nodemailer.
|
|
*/
|
|
export const postContact = (req: Request, res: Response) => {
|
|
req.assert("name", "Name cannot be blank").notEmpty();
|
|
req.assert("email", "Email is not valid").isEmail();
|
|
req.assert("message", "Message cannot be blank").notEmpty();
|
|
|
|
const errors = req.validationErrors();
|
|
|
|
if (errors) {
|
|
req.flash("errors", errors);
|
|
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");
|
|
});
|
|
};
|