Send emails using Gmail and Nodemailer

Isabel Hong
5 min readDec 2, 2020

How to send emails from a gmail account using node’s nodemailer module

Photo by Solen Feyissa on Unsplash

When creating your own web app, one of the cool features you can add is to send emails to your users and to achieve this you can use gmail and nodemailer.

Nodemailer is a module that we can use to send emails using Node JS.

In this tutorial we will do a step by step process to use gmail with nodemailer, and create environment variables to hide your gmail id and password.

Disclaimer: Do not use this method in production without going through OAuth. This tutorial is for learning purposes only.

Requirements for this tutorial:

  • Instead of using your personal account, create a new gmail account for this tutorial or for testing purposes in general.
  • Install node or check your version by typing node -v. in your terminal. It should be 6.0 or higher.

From your terminal create a new project. I called mine gmail_nodemailer . Create a package.json file using the npm init-y command

npm init -y 
//the -y flag is so that a package.json file is generated with default values instead of having to fill out each field step by step

and next install nodemailer.

npm install nodemailer

Using the command line or VS Code create a new file called server.js and import nodemailer at the top of the file.

const nodemailer = require('nodemailer');

To start your node server you need to modify the package.json file by typing in the following “start” line. You can delete the “test” line if you want. I kept it here so that you can compare it with the default one.

"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},

We will cover 3 main steps to use gmail with nodemailer.

  1. Connect gmail with nodemailer using the nodemailer.createTransport() function
  2. Set up sender and receiver details
  3. Send the email using the .sendMail() function

The first step is to use the nodemailer.createTransport() function to connect nodemailer with your email service or provider, in this case gmail. Inside this function we will create an object that contains service and auth.

Here’s the boilerplate from www.nodemailer.com/about adapted for gmail.

const nodemailer = require('nodemailer');let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '',
pass: '' // leave user and pass blank for now
}
});

Using dotenv

Before going into our second step we will install another package in order to protect our email and password from being visible or exposed to the public, for example when you commit this to a github repo. Download the dotenv package and save it as a dependency.

npm install dotenv --save

When reading the official documentation of the dotenv package your will see under Usage: As early as possible in your application, require and configure dotenv.” “As early as possible” means to write the following at line 1 of your file in this case server.js.

require('dotenv').config()

Next create 3 new files. Note the period in front of each file.

  • .env
  • .env-sample
  • .gitignore
  1. Inside your .env file type your email and password information all in capital letters and with no space in between.
EMAIL_ID=example@gmail.com
PASSWORD=examplepassword
// replace the above info with the test gmail account you created for this tutorial

2. Inside your .env-sample file copy paste all except the private information. The reason we create this sample file is in case you want to share your project on a github repo. Others who would want to run your project can fill this file in with their own keys.

EMAIL_ID=
PASSWORD=

3. Inside your .gitignore file type in the files you want git to ignore. We will ignore node_modules and the .env file.

.gitignore file
In your server.js file now use the environment variables like this:let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL_ID,
pass: process.env.PASSWORD
}
});

Set up sender and receiver details

Ok, now the second step is to set up the sender and receiver details using a variable of your choice or let’s say mailOptions and create an object.

let mailOptions = {
from: '"Isabel" <example@gmail.com>', // sender address
to: "test@gmail.com", // receiver address
subject: "Thank you for signing up!", // Subject line
text: "Hello new user, thanks for signing up", // plain text body
html: "<b>Thanks for using our services</b>", // html body
};

Send the email

The third step is to send the email using the .sendMail() function. This function takes in two parameters 1) mailOptions (or the variable you created in the previous step) and 2) a callback function to handle errors if the email is not sent successfully.

transporter.sendMail(mailOptions, function (err, data) {
if (err) {
console.log('error sending email', err);
} else {
console.log('email sent successfully');
}
});

This is the full server.js source code. On line 15 and 16 make sure you replace it with the real email and password info.

server.js source code

An important note on the documentation

Referring back to the nodemailer documentation on using gmail, here is the reason why I initially put a disclaimer at the beginning of this tutorial for not using this method for production.

Even though Gmail is the fastest way to get started with sending emails, it is by no means a preferable solution unless you are using OAuth2 authentication. Gmail expects the user to be an actual user not a robot so it runs a lot of heuristics for every login attempt and blocks anything that looks suspicious to defend the user from account hijacking attempts.

The next paragraph in the documentation Gmail explains the concept of “Less Secure” apps for which we need to go through one last step to be able to test our email setup. Go to this link and switch to ON. https://myaccount.google.com/lesssecureapps

Now run this command and check your receiver and sender email inboxes!

node server.js
Gmail screenshot (the covered part is the sender’s email)

Conclusion

I hope this post was useful to someone as I am looking to better understand Node concepts through coding, writing and studying online with The Hacking School, Hyderabad.

--

--