NodeJS
How to send gmails using Nodemailer from your NodeJS server
May 09, 2020
3 min

Email communication has been playing an important role in most web based applications. For an example informing the users of a product of its upgrades, notifications on a dashboard, and many more. Here we discuss how to build such a email sender using Nodemailer, nodejs and gmail.

Most blogs out there explain how to use Nodemailer in barebones forms. It is rare to find how to use Nodemailer with Gmail, which is the most common application. This blog describes how to set up the nodejs environment, configure nodemailer, and most importantly, how to configure your gmail account so that your node application can access it.

Without much talk, let’s get in action.

Set up the Nodejs project

Whatever the operating system you are using, you need to have Nodejs installed on your computer.
To verify you have installed npm (node package manager) and nodejs, you can run the following commands.

npm -v
node -v

If both of these give a version on your console, then you are good to go. Otherwise, you have to install what is missing. I have mentioned the links of official pages of Node js and npm if you want to dig deeper.

Node Js - https://nodejs.org/en/

Npm - https://www.npmjs.com/

Now, let’s focus on code.

1. Create a folder for the project and go inside it. Open the command prompt or the terminal in that directory.

In my case, i created a folder named “nodemailer-project” on desktop.

2. For initiating the Node project we need a package.json. Hit the following command in the command prompt and do as it says. You will end up on a screen similar to figure 1.

npm init
package name: (nodemailer-project) 
version: (1.0.0) 
description: A simple email sending application
entry point: (index.js) 
test command: 
git repository: 
keywords: 
author: Theekshana Wijewardhana
license: (ISC) 
About to write to /home/theekshana/Desktop/nodemailer-project/package.json:

{
  "name": "nodemailer-project",
  "version": "1.0.0",
  "description": "A simple email sending application",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Theekshana Wijewardhana",
  "license": "ISC"
}
Is this OK? (yes) 

3. Okay, now we have a package.json. We can open our favorite code editor in the same directory.

To open vs code editor on this directory, simply open a terminal on the above folder and hit the below code.

code ./

4. As you see in my package.json, the entry file for my project is index.js. Lets create a index.js

{
  "name": "nodemailer-project",
  "version": "1.0.0",
  "description": "A simple email sending application",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Theekshana Wijewardhana",
  "license": "ISC"
}

Now we have a Node project ready to go…

Tip: we can use nodemon which helps to run the project continuously. Otherwise we will have to hit node index.js again and again. Hit the below command on the terminal.

npm install nodemon

Once it’s successfully installed, we can modify the package.json with a start script as below. This will help us to start a nodemon server.

{
  "name": "nodemailer-project",
  "version": "1.0.0",
  "description": "A simple email sending application",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon"
  },
  "author": "Theekshana Wijewardhana",
  "license": "ISC",
  "dependencies": {
    "nodemon": "^2.0.7"
  }
}

Installing and configuring Nodemailer

To install nodemailer, hit the below command in the terminal.

npm install nodemailer

Once it’s done installing, you can add the below code to index.js. This will import the nodemailer to your project.

const nodemailer = require("nodemailer");

I will describe what we want here after very shortly. They are;

  1. Create a Nodemailer transporter using either SMTP or some other transport mechanism

  2. Set up message options (who sends what to whom)

  3. Deliver the message object using the sendMail() method of your previously created transporter

In the first step, we will be creating a reusable transporter object using the default SMTP transport.

let transporter = nodemailer.createTransport({
    service:'gmail',
    auth: {
        user:'abc@gmail.com', // Your gmail address
        pass: '1234', // password
    },
});

We will be giving the service type to gmail. The auth object specifies the gmail account credentials that we will use to send emails.

The message options consist of four main parameters.

from : The sender of the email

to : The recipient of the email

Subject: The subject of the email

html : all the magic happens here

const messageOptions={
    from: 'samplesender@gmail.com', // sender address
    to: 'hakini8329@httptuan.com', // list of receivers
    subject: "Hello ✔", // Subject line
    text: NodeJs is awesome, // plain text body
    html: `<b>NodeJs is awesome</b>`, // html body
}

Now the last bit is actually sending the email. We can do that by using the sendMail method provided by the transporter object we created above.

let info = await transporter.sendMail(messageOptions);
console.log(info);

Now the code is ready. One more step to go.

Configuring a google account

This is the most important part. There are some points that a developer should really concern when using a gmail account with nodemailer. I will try to summarise some of them below.

“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. For example you might run into trouble if your server is in another geographical location – everything works in your dev machine but messages are blocked in production.”

Yep.. that’s not me. It is a nodemailer saying. If you are doing a project that’s to be deployed in a production environment, then your choice should not be gmail. That’s because Google is really concerned about security and you will get in a lot of trouble adding it to the production. Anyway if the production server is also in the same geo-location, then you can still use gmail with some configurations.

Here are the steps. First you need to allow your google account for less secure apps to access. For that, open your gmail account. There you can see the profile icon on top left. Press on “Manage your google account”

Then on the left tree you can see the security tab. Go inside it. Then you can see something like below which says “Less secure app access”.

nodemailer

If it says off, then you have to switch it on. Now you can try to start your node application running. If it succeeded without any authentication error, walaa… you won the game. If that’s not, yep you have to go another step which is the Captcha Enable challenge. The link for that is given below. After that you can enjoy the project.


Tags

nodejs

Related Posts

NodeJS
How to send Email Attachments with Nodemailer
May 15, 2020
1 min