DEV Community

Scott Robinson
Scott Robinson

Posted on

Using to the Gmail API with Node.js

It's easy to think of a ton of reasons for wanting to connect to your Gmail account programmatically, whether it's to create a bot to send emails on your behalf, or maybe to create your own custom spam filter. There are also endless SaaS ideas for connecting to users' accounts and offering a service on top of Gmail.

Luckily, the Gmail API offers a nice way to manage a Gmail account. With Node.js, we can easily create applications that integrate directly with Gmail. In this article, I'll show how to set up a project, create a Gmail API client, and kickstart your journey with the Gmail API using Node.js.

Setting up the Project

Before diving into the code, let's first set up a new Node.js project. Make sure you have Node.js installed on your system, and then follow the steps below:

  1. Create the project folder: Open your terminal and navigate to where you want your project to reside. Then create a new directory:
   $ mkdir gmail-api-project
   $ cd gmail-api-project
Enter fullscreen mode Exit fullscreen mode
  1. Create a new project: Run the following command and follow the prompts:
   $ npm init -y
Enter fullscreen mode Exit fullscreen mode

The -y parameter tells npm to enter "yes" for all the questions during the init process. So basically, just use all of the defaults.

  1. Install dependencies: We'll be using the googleapis package, so go ahead and install it:
   $ npm install googleapis
Enter fullscreen mode Exit fullscreen mode

Note: Make sure your Node.js version is 10.x or higher, as the Gmail API client may not work correctly with older versions.

The project is now set up and we can move on to creating the actual Gmail API client.

Creating the Gmail API Client

The Gmail API client is the bridge between your code and Gmail. Here's how to create it:

  1. Create credentials in Google Cloud Console: Go to the Google Cloud Console and create a project. Then navigate to "API & Services" > "Dashboard" > "Enable APIs and Services" > search for "Gmail API" and enable it. Now create credentials (OAuth client ID) and download the JSON file.

  2. Load client libraries and credentials: In your project folder, create a new file index.js and add the following code to load the Gmail client libraries and your credentials:

   const {google} = require('googleapis');
   const credentials = require('./path/to/credentials.json');

   const auth = new google.auth.OAuth2(
Enter fullscreen mode Exit fullscreen mode
  1. Authorize the client: Your app will need to obtain an access token to authenticate with Gmail. You can use these tokens by using the following code snippet:
   // Load token or redirect to auth URL

   // Create Gmail client
   const gmail ={version: 'v1', auth});
Enter fullscreen mode Exit fullscreen mode

Be sure to replace 'YOUR_REDIRECT_URL' with the redirect URL you've specified in the Google Cloud Console when creating your OAuth client ID!

Note: In order to obtain the access token, you'll need to set up a way to complete the OAuth flow, which can be done using a few different methods. One possible method to is create an HTTP route that accepts the OAuth credentials and data, but that is outside the scope of this article.

Retrieving Emails

Now that you've set up the Gmail API client, retrieving emails is the next step. Here's how to fetch the emails from your Gmail account with Node.js:

  1. Use the list method: You can use the list method of the Gmail API to fetch emails. For example, let's fetch the last 10 emails:
   const res = await gmail.users.messages.list({
     userId: 'me',
     maxResults: 10

   const messages =;
Enter fullscreen mode Exit fullscreen mode
  1. Get the details of each message: You'll need to call the get method for each message to get the full details:
   for (const message of messages) {
     const msg = await gmail.users.messages.get({
       userId: 'me',
     console.log(`Subject: ${}`);
Enter fullscreen mode Exit fullscreen mode

Here, the list method returns a summary of the messages, so calling the get method for each one is needed to get the rest of the email data.

When creating, I found out the hard way that you'll need a lot of error checking, retries, etc when retrieving emails. The Gmail API often returns HTTP 500 statuses and has lots of edge cases. So make sure you test your applications thoroughly and handle as many potential issues as possible in your code.

Sending an Email

Now that we know how to fetch emails, let's learn how to send an email using the Gmail API.

  1. Create the email content: First, we need to create the email body. You'll have to convert it to a Base64-encoded string:
   const emailLines = [
     'Content-type: text/html;charset=iso-8859-1',
     'MIME-Version: 1.0',
     'Subject: Test Subject',
     'This is a test email'

   const email = emailLines.join('\r\n').trim();
   const base64Email = Buffer.from(email).toString('base64');
Enter fullscreen mode Exit fullscreen mode
  1. Use the send method: Now, you can use the send method to actually send the email via the API:
   await gmail.users.messages.send({
     userId: 'me',
     requestBody: {
       raw: base64Email
Enter fullscreen mode Exit fullscreen mode

And there you have it, you've just sent an email using the Gmail API 👍

Top comments (2)

yash_7200 profile image
Yash Gandhi

how can we block email addresses using gmail api?

ismailisimba profile image
Ismaili Simba

This should be higher, it's surprisingly quite a headache to set this up any other way.