I added to my NodeJS API an endpoint to send an email, for now, is a simple function that sent an email hardcoded and I did it using Send Grid service.
What I would like to achieve now is that I can pass the receiver email in the endpoint request and send the email.
Example of the endpoint url/email/:email
the :email
will be the receiver of the email. I would like to pass this param to my email function which will send there. But I stack as cannot understand how to pass the param inside the sen email like it is now my code.
What I tried so far:
Router
// POST email send
router.post("/email/:email", async (req, res) => {
const email = req.params.email;
try {
const sent = await sendEmail(email);
if (sent) {
res.send({ message: "email sent successfully", status: 200 });
console.log("Email sent");
}
} catch (error) {
throw new Error(error.message);
}
});
// Routes
module.exports = router;
Send email
const mailGenerator = new MailGen({
theme: "salted",
product: {
name: "Awesome Movies",
link: "http://example.com"
}
});
const email = {
body: {
name: receiver here??,
intro: "Welcome to the movie platform",
action: {
instructions:
"Please click the button below to checkout new movies",
button: {
color: "#33b5e5",
text: "New Movies Waiting For you",
link: "http://example.com/"
}
}
}
};
const emailTemplate = mailGenerator.generate(email);
require("fs").writeFileSync("preview.html", emailTemplate, "utf8");
const msg = {
to: receiver here??,
from: "jake@email.io",
subject: "Testing email from NodeJS",
html: emailTemplate
};
const sendEmail = () => {
try {
sgMail.setApiKey(sg_token);
return sgMail.send(msg);
} catch (error) {
throw new Error(error.message);
}
};
module.exports = { sendEmail };