Categories
JavaScript Answers

How to use Nodemailer with Gmail and Node.js?

Spread the love

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: "abc@gmail.com",
    pass: "password"
  }
});

const mail = {
  from: "from <from@gmail.com>",
  to: "to@gmail.com",
  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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *