mirror of
https://github.com/microsoft/TypeScript-Node-Starter.git
synced 2026-03-30 17:10:47 +00:00
initial commit
This commit is contained in:
53
src/controllers/contact.ts
Normal file
53
src/controllers/contact.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import * as 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 let getContact = (req: Request, res: Response) => {
|
||||
res.render("contact", {
|
||||
title: "Contact"
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* POST /contact
|
||||
* Send a contact form via Nodemailer.
|
||||
*/
|
||||
export let 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");
|
||||
});
|
||||
};
|
||||
Reference in New Issue
Block a user