This outline provides a step-by-step breakdown of the code as it was built during the workshop. This file is meant for reference. To see the app in its final state, see the cakeOrPie directory. For a copy of the entire HTML email template, see the emailTemplate directory.
sender.js
const sgMail = require("@sendgrid/mail");
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
to: "[email protected]", // Change to your recipient
from: "[email protected]", // Change to your verified sender
subject: "Your Cake or Pie Order Confirmation",
html: "Thank you for your order. We hope it's <strong>delicious</strong>!",
};
sgMail
.send(msg)
.then(() => {
console.log("Email sent");
})
.catch((error) => {
console.error(error);
});
sender.js
const sgMail = require("@sendgrid/mail");
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
to: "[email protected]", // Change to your recipient
from: "[email protected]", // Change to your verified sender
templateId: "YOUR TEMPLATE ID HERE", // Change to a valid template ID
dynamicTemplateData: {
name: "B. Undt",
},
};
sgMail
.send(msg)
.then(() => {
console.log("Email sent");
})
.catch((error) => {
console.error(error);
});
template name snippet
sender.js
module.exports = function send(email, dynamicData) {
const sgMail = require("@sendgrid/mail");
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
to: email, // Recipient from request
from: "[email protected]", // Change to your verified sender
templateId: "YOUR TEMPLATE ID", // Change to a valid template ID
dynamicTemplateData: dynamicData,
};
sgMail
.send(msg)
.then(() => {
console.log("Email sent");
})
.catch((error) => {
console.error(error);
});
};
index.js
const http = require("http");
const express = require("express");
const sender = require("./sender");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.post("/checkout", (req, res) => {
console.log(`Sending confirmation email to ${req.body.email}`);
res.writeHead(200, { "Content-Type": "application/json" });
sender(req.body.email, req.body.cart);
res.end(`{"success": true}`);
});
http.createServer(app).listen(8080, () => {
console.log("Express server listening on port 8080");
});
sampleREquestBody
{
"email": "[email protected]",
"cart": {
"total": "$114.80",
"items": [
{
"item": "Cupcake variety pack - dozen",
"price": "$19.95"
},
{
"item": "New York cheesecake",
"price": "$34.95"
},
{
"item": "8 inch triple chocolote cake",
"price": "$29.95"
},
{
"item": "Tiramisu",
"price": "$29.95"
}
],
"confirmation_number": "79uxgAMW2q",
"name": "B. Undt",
"address01": "1234 Pretend Pl.",
"city": "Portland",
"state": "OR",
"zip": "97227"
}
}
template receipt snippet