How to Set up Nodemailer with Gmail

On September 27, 2019
6min read
Piotr Malek Technical Content Writer @ Mailtrap

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 explore the secrets behind Nodemailer & Gmail integration.

How to use Nodemailer with Gmail?

The installation and setup 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.

Keep in mind that Google stopped supporting the “Less secure apps” feature in 2022. Therefore, it’s best to take the steps to set up OAuth, otherwise, the method might not work. We won’t go into the details of OAuth setup here, please refer to the official docs linked above.

Setting up a transporter object and a message to be sent

Assuming 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);
  }
});

Create an app.js file and run the code in the terminal with:

node app.js

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 be thinking 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 alternative ways of sending emails in Node.js?

In the example above, we used the sendmail transporter to ship our emails. If this doesn’t work for you, there are 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)
  • 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.

Another recommendation to make your email sending even quicker and more effortless is Mailtrap Email API – an end-to-end sending solution with a capacity to support the sending of up to ∼10000 emails per second via its Email API or SMTP Relay.

On top of that, Mailtrap Email API users get to enjoy other benefits, such as the Actionable Analytics toolset consisting of deliverability alerts, 60-day email logs, and critical metrics dashboards, all intended to help spot and fix early sending issues.

What about onboarding and migration? Both are smooth and straightforward!

With the basic information out of the way, let’s get into the Mailtrap email sending functionality installation and usage.

First, install the NPM package using yarn or npm as follows:

yarn add mailtrap
# or, if you are using NPM:
npm install mailtrap

Once installed, you can send your first email using one of the code snippets below:

Minimal version:

const { MailtrapClient } = require("mailtrap");
// For this example to work, you need to set up a sending domain,
// and obtain a token that is authorized to send from the domain
const TOKEN = "your-api-token";
const SENDER_EMAIL = "sender@yourdomain.com";
const RECIPIENT_EMAIL = "recipient@email.com";
const client = new MailtrapClient({ token: TOKEN });
const sender = { name: "Mailtrap Test", email: SENDER_EMAIL };
client
  .send({
    from: sender,
    to: [{ email: RECIPIENT_EMAIL }],
    subject: "Hello from Mailtrap!",
    text: "Welcome to Mailtrap Sending!",
  })
  .then(console.log, console.error);

Full version:

const sender = { name: "Mailtrap Test", email: SENDER_EMAIL };
const welcomeImage = fs.readFileSync(path.join(__dirname, "welcome.png"));
client
  .send({
    category: "test",
    custom_variables: {
      hello: "world",
      year: 2022,
      anticipated: true,
    },
    from: sender,
    to: [{ email: RECIPIENT_EMAIL }],
    subject: "Hello from Mailtrap!",
    html: `
    <!doctype html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      </head>
      <body style="font-family: sans-serif;">
        <div style="display: block; margin: auto; max-width: 600px;" class="main">
          <h1 style="font-size: 18px; font-weight: bold; margin-top: 20px">Congrats for sending test email with Mailtrap!</h1>
          <p>Inspect it using the tabs you see above and learn how this email can be improved.</p>
          <img alt="Inspect with Tabs" src="cid:welcome.png" style="width: 100%;">
          <p>Now send your email using our fake SMTP server and integration of your choice!</p>
          <p>Good luck! Hope it works.</p>
        </div>
        <!-- Example of invalid for email html/css, will be detected by Mailtrap: -->
        <style>
          .main { background-color: white; }
          a:hover { border-left-width: 1em; min-height: 2em; }
        </style>
      </body>
    </html>
  `,
    attachments: [
      {
        filename: "welcome.png",
        content_id: "welcome.png",
        disposition: "inline",
        content: welcomeImage,
      },
    ],
  })
  .then(console.log, console.error);

If you find yourself needing more information, please refer to the Sending Emails page of the Mailtrap knowledge base.

Testing Nodemailer – Gmail integration

Finally, you should probably allocate some time to testing your newly-configured tools. 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, such as the Mailtrap Email Sandbox, which is part of the Mailtrap Email Delivery Platform along with Email API we mentioned earlier.

Email Sandbox is best described as a safe environment for inspecting and debugging emails in staging before they get sent out to recipients.  

With Email Sandbox, as well as knowing for certain that you aren’t risking spamming users with test emails, you can also preview and check the email content’s spam score and validate the HTML/CSS. 

This is the optimal alternative to manual email testing, which is known for its complexities and damage to domain reputation.

To start using Email Sandbox, you need to integrate it with your app, which takes less than 3 minutes and is done using 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
});

To simplify the development in Nodemailer, you should set both debug and logger to true, as we did above.

And that is it; you’re good to start testing!

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 also be 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 for more information!

Article by Piotr Malek Technical Content Writer @ Mailtrap

Comments

2 replies

Comments are closed.