How to Set up Nodemailer with Gmail

Nodemailer is arguably the most popular module for sending emails from Node.js apps. Gmail, on the other hand, is one of the world’s two most popular email clients. With so many faithful followers, it would seem natural that you can combine both tools and send emails via Google servers. And that’s the case indeed! Join us as we’re exploring the secrets behind Nodemailer & Gmail integration.

How to use Nodemailer with Gmail?

The installation and set up of both accounts are really simple.

Installing Nodemailer

First things first, we need to install Nodemailer. You’ll be good to go if you’re running Node.js 6.0.0+ so any version released since May 2018 will work.

You likely want to use npm:

npm install nodemailer

But Yarn package manager will also work:

yarn add nodemailer

Once Nodemailer is installed, you can use the following code to add it to your app:

const nodemailer = require('nodemailer');

or the following for ES Modules:

import nodemailer from ‘nodemailer’;

Configuring a Gmail account

We’re not going to explain how to set up a Gmail account, you likely already have more than one. Whether you use a free Gmail account or a paid Google account, you need to first configure it for use with Nodemailer.

Launch your client, then click on your profile in the top-right corner -> Google Account -> Security. You’ll see the following setting:

Enable access. While it might not seem like the most secure thing to do, it’s required to let Nodemailer use your Gmail account for mailing purposes.

Also, make sure you complete the Captcha Enable challenge, as following only the step above might not give Nodemailer the sufficient permissions. 

Finally, if your account has two-factor authentication set up and you don’t want to disable it, you’ll need to create an “application-specific password”.

Security first!

Setting up a transporter object and a message to be sent

Since we have both tools set up, we can now add our Gmail credentials to a sendmail transporter object of this node and configure a message. See this example of Nodemailer & Gmail integration:

const nodemailer = require('nodemailer');

const transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'chiefspammer@yourgreatdomain.com',
    pass: 'SuperSecretPassword' // naturally, replace both with your real credentials or an application-specific password
  }
});

const mailOptions = {
  from: 'vindication@enron.com',
  to: 'friendsofenron@gmail.com, enemiesofenron@gmail.com,
  subject: 'Invoices due',
  text: 'Dudes, we really need your money.'
};

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

Note that you can configure different types of callbacks in the last sections of the code. Instead of just getting notified when a message fails to deliver, you could, for example, receive an array including the recipient’s address along with the server response. See all the available options here.

That’s all!

Limitations and possible issues

This was too easy, wasn’t it? To keep the expectations reasonable, let’s talk a bit about the limitations.

Since Gmail accounts are publicly available and used extensively by all types of spammers, Google imposes hard limits on the number of emails sent. At the time of writing, it’s 500 recipients per day. If you were to include two recipients as we did above, this would count as two emails sent already. If you were to send three separate emails to the same recipients, it’s still three emails.

Users on the paid Google Accounts can quadruple their expectations as they can send to up to 2,000 recipients a day. Which should be perfectly fine for sending occasional system updates or transactional emails. But if you have mass marketing campaigns in mind or thousands of users to send emails to, you probably want to look into more sophisticated solutions. Our list of the best transactional email providers might be of use.

One of the issues you might experience is with authentication. “Impossible”, you might think after all the steps we made you take to set up your account. Unfortunately, Google will do its best to make the spammers’ lives miserable and honest users like us often get caught in the crossfire. To counter the potential issues, use oAuth2 with Gmail and Nodemailer. Follow the following instructions.

If this wasn’t enough, you might also get into trouble if your servers are in a different geographic location. Google is easily able to detect such behavior and might flag your activity as suspicious, making it difficult to send out any emails. Finally, you might hit the deliverability issues as you will be sending messages from publicly-available servers. There’s a fair number of spammers and fraudsters utilizing Gmail and even Google Apps accounts and this all affects the reputation of the sending domains.

What are the alternatives to Gmail and Nodemailer?

In the example above we used sendmail transporter to ship our emails. If this doesn’t work for you, there’s a number of other transporters available for use with Nodemailer:

  • SMTP – the main, most universal transporter, easy to use with many ESPs (Email Service Providers)
  • SES – there’s also built-in support for Amazon SES, suitable for large traffic due to its favorable pricing and reliability
  • stream – used for testing purposes as its only role is to return emails

You can also create your own transporter in no time. Have a look at Nodemailer documentation here. Check out also our detailed guide on sending emails with Nodemailer.

Also, if you choose not to use Nodemailer after all, there are several alternatives for sending emails in Node.js. These include Emailjs, ‘email-templates’ package and another one called Mailgen. We’ve described each in more detail in our guide to sending emails in Node.js.

Testing Nodemailer – Gmail integration

Finally, you should probably allocate some time to testing your newly-configured toys. While you could test a few possibilities by just putting your email address in the ‘to’ field in the code, it won’t be so easy with the higher volume. That’s why you should consider using a tool made specifically for email testing. One such option is Mailtrap.

Mailtrap lets you set up a testing environment for all your automatic emails. It takes minutes to configure (code example available). When connected, it will capture all your outgoing messages, letting you preview and analyze them before they’re sent for real.

To use it, create a free Mailtrap account. To simplify the development in Nodemailer you can set both debug and logger to true.

Then, replace your Gmail credentials from the code above with Mailtrap ones. Use the following code:

const transport = nodemailer.createTransport({
  host: "smtp.mailtrap.io",
  port: 2525,
  auth: {
    user: "43f12e1ab123c2", // replace with your Mailtrap credentials
    pass: "your_password"
  },
  debug: true, // show debug output
  logger: true // log information in console
});

You’re good to go!

Wrapping up

As you can see, using Gmail with Nodemailer is really easy. The same goes for the more sophisticated email sending providers. Many provide detailed instructions for integrating Nodemailer along with code samples.

As you probably know, Nodemailer can be also used with other JavaScript frameworks and libraries and the very same steps for utilizing a Gmail account apply too. In other posts, we explained in detail how to use Nodemailer in applications built with Angular, ReactJS and even React Native. Check them out!