How to send Email with NodeJS in 2022
Tags: javascript, node, nodemailer, vkassingh
Published: 2022-10-30 07:25:07


![send email in nodejs using nodemailer and gmail](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/738k1q41qs86qb2soovr.png)

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
```

Now install Nodemailer 

```
npm i nodemailer
```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l50a0p0ci1fjxyej54do.jpg)

Then click on **Select app** option as shown in the picture.
![send email nodejs nodemailer](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j5a933y5zziq6vc1yc3i.jpg)

Enter any meaningful name for the app like I have named it **NodejsApp**. Then click on **Generate** button as shown.
![send email nodejs nodemailer](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jh9g2dq54nuasm23i5mq.jpg)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3e8l4koy34p8ijrec7fr.jpg)


## 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"
    }

})
```

## 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"
}

```

## 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")
    }
})


```

## 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
    }
```

## 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")
    }
})
```

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.