How to use Nodemailer with Gmail and Node.js?

Sometimes, we want to use Nodemailer with Gmail and Node.js.

In this article, we’ll look at how to use Nodemailer with Gmail and Node.js.

How to use Nodemailer with Gmail and Node.js?

To use Nodemailer with Gmail and Node.js, we use the createTransport and sendMail methods.

For instance, we write

const mailer = require("nodemailer");
const smtpTransport = mailer.createTransport("SMTP", {
  service: "Gmail",
  auth: {
    user: "[email protected]",
    pass: "password"
  }
});

const mail = {
  from: "from <[email protected]>",
  to: "[email protected]",
  subject: "Send Email Using Node.js",
  text: "Node.js",
  html: "<b>Node.js</b>"
}

smtpTransport.sendMail(mail, (error, response) => {
  if (error) {
    console.log(error);
  } else {
    console.log(response.message);
  }
  smtpTransport.close();
});

to call mailer.createTransport to create the smtpTransport object that we use to log into our SMTP server.

Then we call smtpTransform.sendMail to send our email with the data coming from the mail object.

If there’s an error, then error is set in the callback.

Otherwise, response is set.

Finally, we log out of the SMTP server with smtpTransport.close.

Conclusion

To send emails in Node.js, we can use the nodemailer package.