DEV Community

Cover image for Node.js Emailing: Get Started with Nodemailer
Muhammed Sahad
Muhammed Sahad

Posted on

Node.js Emailing: Get Started with Nodemailer

Read This On Medium https://medium.com/@muhammedsahad/node-js-emailing-get-started-with-nodemailer-5dccaed6eb3f

Hey folks! In this quick tutorial, I’ll show you how to implement Nodemailer in just a few simple steps. It’s going to be a short and sweet guide, so let’s dive right in!

What is Nodemailer ?

Nodemailer is a module for Node js applications for sending mails. you can check the official website here

Creating App Password

Before we begin, we need to setup the app password. A Google App Password is a 16-digit passcode that allows apps or devices that don’t support two-factor authentication (2FA) to connect to your Google account securely. so let create app password

First login your Google Account Manger:

Image description

Search for App Password:

Image description

Let’s create an app password

Image description

The you can see the 16 digit password created keep it secure do not expose it.

Image description

Setup Nodemailer

Now, Lets setup the Nodemailer. We have Nodemailer package available in NPM. click here to see

Install nodemailer package

npm i nodemailer
Enter fullscreen mode Exit fullscreen mode

Configure Nodemailer

var nodemailer = require("nodemailer");

var transporter = nodemailer.createTransport({
  service: "gmail",
  host: "smtp.gmail.com",
  port: 465,
  secure: true,
  auth: {
    user: process.env.RECIPIENT_EMAIL_ADDRESS,
    pass: process.env.RECIPIENT_EMAIL_PASSWORD,
  },
});

module.exports = transporter;
Enter fullscreen mode Exit fullscreen mode

Now replace with app password that you created and your email address with pass and user .

Now we are gonna send email. i’ve a route called /send-mail


router.post("/send-mail", (req,res) => {
  try {

      var mailOptions = {
        from: `jhon@gmail.com`,
        to: "sahadmuhammed289@gmail.com",
        subject: "Sending Email With Nodemailer",
        text: "Email Received!",
        name: "Jhon"
      };

      transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
          console.log(error);
        } else {
           console.log("Mail Sent!")
        }
      });
    } catch (error) {
      console.log("ERROR:", error);
    }
});
Enter fullscreen mode Exit fullscreen mode

you can see the mailOptions Object which held the info of our mail. replace to with email which you wanna receive the the emails. If any error happen when sending the email, the error in the sendMail logs it. if everything is work perfect you can get the email and the log “Mail sent”.

Here is the result

That’s all ! 😃

If you got something from this post please clap and leave your doubts on comments. see you on next blog.

Top comments (0)