Node JS Tutorial - Send Email using Gmail

In this tutorial, we will learn how to send an email using Gmail in Node.js.

To achieve this, we will use the Nodemailer module, which is a popular Node.js npm module that allows us to send emails easily.

Installing Nodemailer

First, we need to install the Nodemailer module. To do this, go to the command prompt and run the following command:


npm install nodemailer

Configuring Nodemailer

Next, go to the index.js file and require the Nodemailer module:


const nodemailer = require('nodemailer');

Then, call the createTransport method and pass the service and auth options:


var transporter = nodemailer.createTransport({
service:'gmail',
auth:{
user:"yourgmailid@gmail.com",
pass:"yourpassword".
}
});

Set the mail options:


var mailOptions = {
from:'testmail@gmail.com',
to:'testmail@gmail.com',
subject:'NodeJs Test Mail',
text:'This is test mail from node js application'.
};

Finally, call the sendMail method:


transporter.sendMail(mailOptions,function(err,info){
if(err)
{
console.log(err);
}
else{
console.log('Email Sent:' + info.response);
}
});

Enabling Less Secure App Access in Gmail

To allow Nodemailer to send emails using your Gmail account, you need to enable less secure app access. To do this, go to your Gmail account settings, click on "Account", then click on "Security", and finally turn on "Less secure app access".

Testing the Email Sending

Now, let's test our email sending functionality. Go to the command prompt and run the index.js file:


node index.js

If everything is set up correctly, you should see a message indicating that the email has been sent.

Go to your Gmail inbox, and you should see the email that was just sent.

That's it! You have now learned how to send an email using Gmail in Node.js.