Install Nodemailer
If you want to learn more about Nodemailer you can read here:
https://www.npmjs.com/package/nodemailer
Turn on the Terminal and type the following command to install
npm i nodemailer
Handling Send Mail
The outermost of the project creates the file as follows the following folder
Code handle send mail (sendMail.js)
const nodemailer = require("nodemailer"); const transport = nodemailer.createTransport({ service: "Gmail", auth: { user: Email name you use to send, pass: Email password you use to send, }, }); module.exports.sendConfirmationEmail = (name, email) => { transport .sendMail({ from: user, to: email, subject: "Confirm your registered account", html: `<h1>Email Confirmation</h1> <h2>Hello ${name}</h2> <p>You have successfully registered an account. Please confirm your email by clicking on the following link</p> </div>`, }) .catch((err) => console.log(err)); };
Handling Router
Code handle router (router.js)
Add the following code to the router .js
const sendMail = require("../utils/sendMail"); router.post("/sendmail", async (req, res, next) => { try { sendMail.sendConfirmationEmail(req.body.name, req.body.email); return res.status(200).send("Oke"); } catch (err) { console.log("🚀 ~ file: Routers.js:11 ~ router.post ~ err", err); next(err); } });
Run test results
Here I use insomnia to test API
Check mail
Conclusion
We have successfully implemented email notification functionality using Nodemailer. In the next posts, we will explore deeper into system architecture and security. You can follow all my upcoming technical insights and lifestyle updates at Lê Phương Trung - Middle Fullstack Developer.
If you do not understand something, feel free to message me or join our Zalo community: Join Node.js Backend Group to exchange knowledge about Node.js and Backend development!



Top comments (0)