DEV Community

LePhuongTrung
LePhuongTrung

Posted on

Complete code Send mail on node JS for 60s

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

handle sendMail

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

insomnia

Check mail

Check mail

Conclusion

If you do not understand something, you can message me or join this group Zalo: Link, to exchange knowledge about BackEnd Nodejs

Top comments (0)