Categories
JavaScript Answers

How to use Nodemailer with Gmail and Node.js and JavaScript?

Spread the love

To use Nodemailer with Gmail and Node.js and JavaScript, we call the sendMail method.

For instance, we write

const nodemailer = require("nodemailer");
const smtpTransport = require("nodemailer-smtp-transport");

const transporter = nodemailer.createTransport(
  smtpTransport({
    service: "gmail",
    host: "smtp.gmail.com",
    auth: {
      user: "somerealemail@gmail.com",
      pass: "realpasswordforaboveaccount",
    },
  })
);

const mailOptions = {
  from: "somerealemail@gmail.com",
  to: "friend@gmail.com",
  subject: "Sending Email using Node.js[nodemailer]",
  text: "That was easy!",
};

transporter.sendMail(mailOptions, (error, info) => {
  if (error) {
    console.log(error);
  } else {
    console.log("Email sent: " + info.response);
  }
});

to create a transporter object with the createTransport method.

We call it with the object returned by smtpTransport with the username, password, and server host name to send email via SMTP.

Then we create the mailOptions object with the email options.

We call transporter.sendMail method with the mailOptions to send the message.

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 *