Categories
JavaScript Answers

How to send emails in Node.js?

Spread the love

Sometimes, we want to send emails in Node.js.

In this article, we’ll look at how to send emails in Node.js.

How to send emails in Node.js?

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

To install it, we run

npm i nodemailer

Then we use it by writing

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();
});

we 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 *