Using to the Gmail API with Node.js
Tags: node, gmail, api
Published: 2023-08-16 16:57:41

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](https://nodejs.org/) 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:

   ```bash
   $ mkdir gmail-api-project
   $ cd gmail-api-project
   ```

2. **Create a new project:** Run the following command and follow the prompts:

   ```bash
   $ npm init -y
   ```

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

3. **Install dependencies:** We'll be using the `googleapis` package, so go ahead and install it:

   ```bash
   $ npm install googleapis
   ```

   **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](https://console.cloud.google.com/) 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:

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

   const auth = new google.auth.OAuth2(
     credentials.client_id,
     credentials.client_secret,
     'YOUR_REDIRECT_URL'
   );
   ```

3. **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:

   ```javascript
   // Load token or redirect to auth URL
   auth.setCredentials(tokens);

   // Create Gmail client
   const gmail = google.gmail({version: 'v1', auth});
   ```

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:

   ```javascript
   const res = await gmail.users.messages.list({
     userId: 'me',
     maxResults: 10
   });

   const messages = res.data.messages;
   ```

2. **Get the details of each message:** You'll need to call the `get` method for each message to get the full details:

   ```javascript
   for (const message of messages) {
     const msg = await gmail.users.messages.get({
       userId: 'me',
       id: message.id
     });
     console.log(`Subject: ${msg.data.subject}`);
   }
   ```

   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 [blocksender.io](https://blocksender.io/), 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:

   ```javascript
   const emailLines = [
     'From: sender@example.com',
     'To: receiver@example.com',
     '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');
   ```

2. **Use the `send` method:** Now, you can use the `send` method to actually send the email via the API:

   ```javascript
   await gmail.users.messages.send({
     userId: 'me',
     requestBody: {
       raw: base64Email
     }
   });
   ```

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