Accessing Mailbox Using the Gmail API and Node.js

Written by

The Gmail API grants secure access to messages, threads, and labels and allows developers to create a variety of different applications for mail indexing, label management, and message sending.

In this tutorial, you will learn how to create a simple app that can grant access to a Gmail account, filter the list of messages, and assign them a specific label. The code shown here is written in Node.js but you can easily adapt it to your preferred language.

Create a Project in Google API Console

First, create a project in the Google Developers Console. Visit https://console.developers.google.com/ and log in, then click on Select a project > NEW PROJECT.

Google developer console

Enable the Gmail API Library

Navigate to the Library, search for the Gmail API and enable it.

Gmail API

Configure OAuth Consent Screen

Before creating the credentials, configure the OAuth consent screen by clicking on the button CONFIGURE CONSENT SCREEN.

OAuth Consent Screen

Select the User Type depending on the users who will be able to use the application.

External User Type

Type the application name and click Save.

OAuth Consent Screen

Create Credentials

In the left menu, click on Credentials > CREATE CREDENTIALS, and select OAuth client ID.

OAuth Client Id

Select the application type and enter a name for the credentials.

Create OAuth Client Id

You should be able to see the new credentials under the OAuth 2.0 Client IDs section. Click on the download icon to download the credentials file. Then rename it to credentials.json.

API Credentials

Set Up the QuickStart Example

Navigate to the Node.js Quickstart page, copy the quickstart example provided by Google, and save it in a file named index.js.

Gmail API Sample

In the Terminal window, go to the Working Directory where you created the file index.js, and run the command yarn add googleapis@39 to install the Gmail API library.

Then run the command node . to execute the sample code. The first time you will be asked to authorize the application by visiting a URL like the example below. Open that URL in a browser and follow the steps. At the end, you will get a code that you have to paste in the terminal window right where it says “Enter the code from that page here.”

Authorize this app by visiting this url: https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fgmail.readonly&response_type=code&client_id=479559853488-050lms0ffusprdhh938s954q0s36kg4i.apps.googleusercontent.com&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob
Enter the code from that page here:

After the app is successfully authorized, a list of the current labels from the user’s mailbox is shown.

Labels:- CATEGORY_PERSONAL- CATEGORY_SOCIAL- CATEGORY_UPDATES- CATEGORY_FORUMS- CATEGORY_PROMOTIONS- CHAT- SENT- INBOX- TRASH- DRAFT- SPAM- STARRED- UNREAD

Custom the Example Code

The authorize function in the quickstart example is in charge of validating the credentials and generating the token. You have to send the constant oAuth2Client as a parameter for the functions listed in the next sections.

functionauthorize(credentials, callback) {  
  ...  
  const oAuth2Client = new google.auth.OAuth2(      
    client_id, client_secret, redirect_uris[0]);  
  ...}

Now, in order to be able to manage the labels of the messages, you need to change the initial scope from gmail.readonly to gmail.modify.

const SCOPES = ['https://www.googleapis.com/auth/gmail.modify'];

Also, delete the token.json file from your working directory.

Then, go to the listLabels function and add the label id in the console log.

functionlistLabels(auth) {  
  ...      
    labels.forEach((label) => {        
      console.log(`- ${label.name} : ${label.id}`);      
    });  
  ...}

Finally, run the application by using the command node . to authorize the app again and update the access permissions. You should be able to see the label list but now each label with its corresponding id.

Labels:- CATEGORY_PERSONAL : CATEGORY_PERSONAL- CATEGORY_SOCIAL : CATEGORY_SOCIAL- CATEGORY_UPDATES : CATEGORY_UPDATES- CATEGORY_FORUMS : CATEGORY_FORUMS- CATEGORY_PROMOTIONS : CATEGORY_PROMOTIONS- CHAT : CHAT- PENDING : Label_11- SENT : SENT- INBOX : INBOX- TRASH : TRASH- DRAFT : DRAFT- SPAM : SPAM- STARRED : STARRED- UNREAD : UNREAD

List Messages

The list messages function uses the gmail.users.messages.list to list the messages that meet the criteria given by the query param.

functionlistMessages(auth, query) {  
  return new Promise((resolve, reject) => {    
    const gmail = google.gmail({version: 'v1', auth});    
    gmail.users.messages.list(      
      {        
        userId: 'me',        
        q: query,      
      },            (err, res) => {        
        if (err) {                    reject(err);          
          return;        
        }        
        if (!res.data.messages) {                    resolve([]);          
          return;        
        }                resolve(res.data.messages);      
      }    
    );  
  })
;}

You can call this function as follows:

const messages = await listMessages(oAuth2Client, 'label:inbox subject:reminder');

This will retrieve all messages from the inbox with a subject that includes the word “reminder.”

Modify Labels

You can modify the label of any message by using this function.

functionmodifyLabels(auth, messageId, addLabelIds, removeLabelIds) {  
  returnnew Promise((resolve, reject) => {    
    const gmail = google.gmail({version: 'v1', auth});    
    gmail.users.messages.modify(      
      {        
        id: messageId,        
        userId: 'me',        
        resource: {          
          addLabelIds,          
          removeLabelIds,        
        },      
      },            (err, res) => {        
        if (err) {                    reject(err);          
          return;        
        }                resolve(res);        
        return;      
      }    
    );  
  });
}

Loop through the previous messages. Call the modifyLabels functions with the right parameters.

This call will remove the INBOX label and will add the PENDING label to all the messages. Label_11 is the id of the label PENDING that we created using the Gmail site.

messages.forEach(msg => {      modifyLabels(oAuth2Client, msg.id, [Label_11], ['INBOX']);})

For sake of simplicity, we created and retrieved the id of the PENDING label manually. However, the Gmail API provides the methods that will let you do that programmatically. We encourage you to check the API Reference by visiting Gmail API Documentation.

Let us know how you did!

Conclusion

Using techniques like what is listed above, we have had the opportunity to address our clients’ concerns and they love it! If you are interested in joining our team, please visit our Careers page.

---
At FullStack Labs, we are consistently asked for ways to speed up time-to-market and improve project maintainability. We pride ourselves on our ability to push the capabilities of these cutting-edge libraries. Interested in learning more about speeding up development time on your next form project, or improving an existing codebase with forms? Contact us.

Learn more

Frequently Asked Questions