How to send emails securely using Gmail and NodeJS

Edigleysson Silva
7 min readMar 8, 2021

--

Sending emails is a common feature that is present in many applications. This feature is used to notify user about news, like a newsletter, about your product status when it's facing to an issue, recovery password and so on.

To send emails you will need an application to create the emails and call the SMTP server to send, which is what we will do here using NodeJS and an SMTP server, which we will not do here.

But don’t worry, we have a great and powerful solution to use as your SMTP server. Stay with me and let’s go together!

Step 1: The SMTP server

From SendGrid we have:

A SMTP (Simple Mail Transfer Protocol) server is an application that’s primary purpose is to send, receive, and/or relay outgoing mail between email senders and receivers.

If you’re thinking now, “Okay, we need an SMTP server. But how does this relate to Gmail? If it’s in the title of the article, it should be mentioned in the content, right?”

I have to say that you are right! We need and will talk about Gmail here.

Step 2: How can Gmail help us?

One of the most popular webmail clients with 1.8 million users is Gmail. As you may already know, this is Google’s webmail client and for handling emails it has its own SMTP server.

Every SMTP server has an address that is used to send emails. In addition to the address, you (common and recommended) will need authentication and with Gmail, it is no different.

It has an address that you can connect to and authenticate with your Gmail account. What you need to connect with the Gmail SMTP server is listed below.

  • Address: smtp.gmail.com
  • Requires SSL: Yes
  • Requires TLS: Yes (if available)
  • Requires Authentication: Yes
  • Port for SSL: 465
  • Port for TLS/STARTTLS: 587

I know it is a considerable amount of information, especially if you have never had contact with SMTP. But, again, don't worry.

In the next step, we'll handle this in a really simple way.

Step 3: Let's connect with the SMTP server using Nodemailer

In this article, we'll use the Nodemailer to handle SMTP in NodeJS. From the official Nodemailer website we have:

Nodemailer is a module for Node.js applications to allow easy as cake email sending. The project got started back in 2010 when there was no sane option to send email messages, today it is the solution most Node.js users turn to by default.

Let’s set up Node with Nodemailer. By following the steps, you will achieve it:

3.1 Creating the project

Go to your workspace folder, create a folder for this project and init the project using npmlike is shown below:

cd ~/projects/ # go to the projects folder
mkdir node-sending-emails # created a folder to this project
cd node-sending-emails # move to the created folder
npm init -y # initializer the project with default config

3.2 Installing the nodemailer

Now that you already created the project you can install the dependencies using npm. See how:

npm install nodemailer #installs the nodemailer package

Great! The nodemailer is now available. Let's connect to the SMTP server.

3.3 Connecting with the Gmail

Nodemailer is really simple to use. To send an email we need to a transporter object. This object encapsulates the operations of checking connections and sending emails.

Se we basically need to create a transport with the configurations of the SMTP server that we'll use. As you can see below:

const nodemailer = require('nodemailer');const transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 587,
auth: {
user: 'youremail@gmail.com',
pass: 'yourpassword',
},
});
transporter.verify().then(console.log).catch(console.error);

The above code uses nodemailer to create the transporter with the information that we already know about the Gmail SMTP server.

After create transporter we call the verify() method to try to connect with the server and show the connection info when the execution gets success, and error when the execution gets fail.

3.4 Running the script

Awesome!! We can finally connect with the server. Once we execute this code we got to the glory! So let's run it and check the results.

Image 1 — Result from execution

Ok… It's not so good. We got an error :/

Again… don't worry. It's was expected. Gmail has some layers of security, so you can't just connect and send a million of emails. Before it you need to set up few things in your Gmail account to make it work.

If you look at the account you used in the example, you will find that something a security alert is shown as in the image below.

Image 2 — Security alert from Gmail

This is an email sent by Google that notifies me of a login attempt made with my password, which was us. When we try to connect to Gmail using a third party application (created by us) it blocks because it considers that application to be insecure.

In the next step, we resolve this. Let’s move on!

Step 4: Configure Gmail account to accept less secure apps

Our application is classified as insecure by Gmail. To bypass it we can configure our account to allow insecure apps to connect with our account. When this configuration is enabled all apps with username and password can connect to our account in Gmail and send emails.

To enable it you need to go to https://myaccount.google.com/ and select your Google Account. Then go to Security in the left sidebar and search by "Less secure app access". You'll see something looks like

Image 3 — Enabling less secure apps in Gmail

Turn on and run the code again. It should work fine and you'll see a true in your terminal.

Really awesome! We're now connected to the Gmail. But no email was sent, right?

Yes. We only verified the connection with the verify() method. Let's get to know a new method and send an email.

4.1 Definitely sending emails

The transporter object has a method called sendMail() that is responsible to send emails effectively. This method receives an object with some parameters. The main parameters are: from, to, subject, text, and html.

That are email sender, list of receivers separated by a comma (,), the email subject, the email content in text plain, and the email content in HTML (if you desire) respectively.

And we have a trick to send emails with Gmail in Nodemailer. Actually, we don't need to go through all the SMTP settings. We only need two configurations to set a transporter to connect with Gmail. See the complete example below.

Note that in the createTransport we only pass an attribute called service where we define it asgmail and the auth with our credentials.

In the sendMail() we pass all data about email. That's all. Try to run this example again and see the result. If it works well, you'll get something as shown below in your terminal.

{
info: {
accepted: [ 'receiver@gmail.com' ],
rejected: [],
envelopeTime: 871,
messageTime: 651,
messageSize: 747,
response: '250 2.0.0 OK 1615152446 m6sm5222884qtx.3 - gsmtp',
envelope: { from: 'fromemail@gmail.com', to: [Array] },
messageId: '<95e9c9a0-9c20-fcda-1873-7f16aec2b293@gmail.com>'
}
}

And in the receiver.

Image 4 — Gmail inbox with the received email

And in the sender.

Image 5 — Gmail outbox with the sent email

Step 5: Keep your Gmail account and your application secure

Our application is working fine, right? I don't know. Use less secure apps is so weird to me. There is a way to improve it and make this access to Gmail more secure. We can do this using App Password.

App Password is a feature that allows us to generate a password for each app. This feature can be useful once you won't provide your own password but a password for that app.

5.1 How to make it happen?

Go to https://myaccount.google.com/ and in the left sidebar click in Security, find "Signing in to Google", click in 2-Step Verification and enable it.

After enabling 2-Step Verification you'll see another option that is App Passwords. Click on this option and you'll see a page like the one shown below in the image.

Image 6 — App passwords

To create a new app password click "Select app" combobox, select Other, define a name and click in Generate. A dialog box will appear with the password. See below.

Image 7 — Generated new app password

Replace the password you entered in the code with the generated app password and you're done. Now you can disable the option "less secure apps" and manage your app passwords.

Summary

Sending emails is a powerful feature and not difficult to implement. We saw in this article how to implement it simply, quickly, and safely.

With the concepts of this article, you are able to handle emails using not only Gmail but other providers like Outlook and the own providers that exist. Be creative, create great applications and share with us.

Please clap 👏👏 and share this post if it was useful to you. Thanks for reading. See ya!

You may be interested in

References

--

--