DEV Community

Cover image for How to send Email with NodeJS in 2022
Vikas Singh
Vikas Singh

Posted on

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.

Top comments (4)

Collapse
 
pcjmfranken profile image
Peter Franken • Edited

This method might leak your system hostname (i.e. your computer name) in the sent email headers. I believe Nodemailer provides some additional configuration options to prevent this local hostname resolution.

For sending business email you could also opt to use the email provider's API. This might be a bit more convoluted to set up, but gives you far greater control over permissions and such:

Collapse
 
vkassingh profile image
Vikas Singh

Thanks @pcjmfranken for pointing it out . It can be a secuirty issue. I will try to fix it .

Collapse
 
akashpattnaik profile image
Akash Pattnaik

Hey Vikas! Thanks for writing this article. I had written this project about a year ago and last May google closed less secure apps so I thought this was over. Now it seems it can be restarted again.

Collapse
 
vkassingh profile image
Vikas Singh

Yes Akash , this project can be started again. I have mentioned the steps to use Gmail as a service in the post. You can refer those steps.