How to send Email with NodeJS in 2022

vkassingh

Vikas Singh

Posted on October 30, 2022

How to send Email with NodeJS in 2022

send email in nodejs using nodemailer and gmail

G'day everyone.Today we will learn how to send emails with NodeJS using Nodemailer and gmail account.

What we will learn :

  1. Sending emails in nodejs
  2. How to debug if any error encounters.

Getting started with Project

First Intialise the project with this command.

npm init -y
Enter fullscreen mode Exit fullscreen mode

Now install Nodemailer

npm i nodemailer
Enter fullscreen mode Exit fullscreen mode

Then create a file and name it sendMail.js.
Now we have to do the following 4 things to acheive our goal.

  1. Configure your Gmail account to send emails with any 3rd party app (Nodemailer).
  2. Create a MailTransporter object.
  3. Create a MailOptions object
  4. Use MailTransporter.sendMail method to send mail.

1. Configure your gmail account

To send email through Gmail and any third-party app like Nodemailer, you have to First enable 2-step verification under Security section on the Gmail account. Then you have to generate App password. For this, click on App passwords

send email nodejs nodemailer

Then click on Select app option as shown in the picture.
send email nodejs nodemailer

Enter any meaningful name for the app like I have named it NodejsApp. Then click on Generate button as shown.
send email nodejs nodemailer

Then you will get the password to use inside the yellow box. Let's call it generated app password. This password will be used in the project later on, so save it carefully
send email NodeJS nodemailer

2. Create a mailTransporter Object

Require the nodemailer. Then use nodemailer.createTransport({}) method to create Transporter object. This method takes an object that specify about the service to be used(gmail in our case), auth object, sender email id and password.

const nodemailer= require('nodemailer')
let mailTransporter= nodemailer.createTransport({

    service: "gmail",
    auth: {
        user: "sender mail address",
        pass: "Generated app password"
    }

})
Enter fullscreen mode Exit fullscreen mode

3. Create MailOptions Object

Create an object named MailOptions. This object specifies senders mail address, recievers address, subject of the mail, text message for mail.

let MailOptions= {
    from: "sender mail address",
    to: "receiver mail address",
    subject: "testing nodemailer",
    text: "testing 123"
}

Enter fullscreen mode Exit fullscreen mode

4. Send mail

Then finally use TransporterName.sendMail() method. It takes MailOptions as first argument and an error first call back function as 2nd argument.

MailTransporter.sendMail(MailOptions, (err)=>{
    if(err){
        console.log(err.message)
    }

    else {
        console.log("email sent")
    }
})


Enter fullscreen mode Exit fullscreen mode

Error and Debugging

On running the above script, I got this error.
"self signed certificate in certificate chain".
This error means that the host does not have a valid certificate. Thats why we get the error. Then I tried to search it on google. And I got the solution. First on stack overflow and then on GitHub.

https://stackoverflow.com/questions/46742402/error-self-signed-certificate-in-certificate-chain-nodejs-nodemailer-express
https://github.com/nodemailer/nodemailer/issues/406#issuecomment-83941225

What I learnt:
I learnt that we can allow that self signed certificate by using tls.rejectUnauthorized option in our MailTransporter object. We have to add the following code in the MailTransporter object to resolve the error.

tls: {
        rejectUnauthorized: false
    }
Enter fullscreen mode Exit fullscreen mode

Full Code for sendMail.js

const nodemailer= require('nodemailer')

let MailTransporter= nodemailer.createTransport({

    service: "gmail",
    auth: {
        user: "sender mail address",
        pass: "Generated app password"
    },
    tls: {
        rejectUnauthorized: false
    }
})

let MailOptions= {
    from: "sender mail address",
    to: "receiver mail address",
    subject: "testing nodemailer",
    text: "testing 123"
}

MailTransporter.sendMail(MailOptions, (err)=>{
    if(err){
        console.log(err.message)
    }

    else {
        console.log("Email Sent")
    }
})
Enter fullscreen mode Exit fullscreen mode

On running this, the email will be sent from the server and you will get a message "Email sent" in the console.
Hope you learnt something new in this blog. Please share your views in the comments section.

💖 💪 🙅 🚩
vkassingh
Vikas Singh

Posted on October 30, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

How to send Email with NodeJS in 2022
javascript How to send Email with NodeJS in 2022

October 30, 2022