How to Use the Gmail API

How to Integrate the Gmail API Into Your App

15 min read
Tags:

The Gmail API is a RESTful interface that provides access to all of the data and functionality in Gmail mailboxes, enabling developers to parse email data, create email drafts, send emails, organize an email inbox with labels, modify settings for user accounts, and create filters to automatically label, forward, or archive emails. Here at Nylas, we spend a ton of time integrating with third-party APIs, like the Gmail API, to build our Email API, so we’re here to offer our expertise about what it takes to build a full integration with Gmail.

Do you want to integrate Gmail accounts directly into your app? This article will  cover the major components of the Gmail API. It will also demonstrate how the Nylas Platform abstracts away much of the complexity of building a direct integration with the Gmail API to enable you to build your email integration much more quickly and efficiently.

Contents:

Want a faster way to integrate Gmail accounts into your app? Check out the Nylas Email API quickstart guide.

Connect Gmail Accounts To Your App

Before you can access a Gmail account, you will need to authenticate the account with the appropriate permissions. All Google APIs use OAuth 2.0 for account authentication and authorization, which establishes a login process where your app negotiates with the Google Identity Platform to receive an access token for user accounts. This token provides limited access to user resources based on the scopes the user consented to as part of the authentication process. Take a look at our guide on Google OAuth to learn about the various methods used to authenticate to Google APIs.

Use Nylas to Connect Gmail Accounts

Alternatively, Nylas Hosted Auth auto-detects Google accounts, even for domains other than gmail.com, and prompts users to sign in and accept the permissions your app needs. Your user’s credentials are stored safely on our SOC 2 Certified infrastructure, and Nylas provides an access token your app can use for Gmail data and functionality.

Illustration of the Nylas Hosted Auth service that integrates with 100% of email, calendar, and contacts providers, including Google

How to Read Email Messages and Manage Labels

Messages and labels are the fundamental building blocks of the Gmail API, this section will cover how to work with these resources.

Messages

Messages are resources that represent a single email; with the Gmail API, you can only create and delete messages, and apply labels to them, all other data is immutable and can’t be changed. Messages can exist on their own, or be a part of a draft or thread:

  • Draft – An unsent message that with the label DRAFT. When sent, it’s automatically replaced with a matching message that has the label SENT; more on this later.
  • Thread – A collection of messages that represents a conversation. Gmail creates threads automatically as users send and receive emails. With the Gmail API, you can delete threads and insert messages into existing threads.

The Nylas Platform makes it super easy to access full data and functionality for messages, threads, and drafts. You can use the Threads endpoint to return information about all of the messages in a thread, including the subject, email participants, unread status, a snippet from the most recent email, and more:

$ curl -X GET 'https://api.nylas.com/threads?limit=1' -H 'Authorization: Bearer ACCESS_TOKEN' 
[
  {
      "subject": "Incredible Wireless Technology!",
      "snippet": "Have you heard about this cellular technology?",
      "unread": false,
      "has_attachments": true,
      "folders": [
          {
              "display_name": "Inbox",
              "id": "a34e45dfvqd2q424fa",
              "name": "inbox"
          }
      ],
      "message_ids": [
          "nbjs8fsj38fjjt0ll7",
          "hjdgfd823j45hgf7j3nn48"
      ],
      "participants": [
          {
              "name": "Alexander Graham Bell",
              "email": "[email protected]"
          },
          {
              "name": "Nikola Tesla",
              "email": "[email protected]"
          }
      ],
    ...
  }
]

Then, if you want to get more detailed information about the individual email messages, you can query the Messages endpoint to return the full email body, list the file attachments, find more specific info about the participants, and more:

$ curl -X GET 'https://api.nylas.com/messages/nbjs8fsj38fjjt0ll7' -H 'Authorization: Bearer ACCESS_TOKEN'
{
  "subject": "Incredible Wireless Technology!",
  "body": "Have you heard about cellular technology? I hear some people are using it for wireless phone devices.",
  "unread": true,
  "from": [
      {
        "name": "Nikola Tesla",
        "email": "[email protected]"
      }
  ],
  "to": [
      {
        "name": "Alexander Graham Bell",
        "email": "[email protected]"
      }
  ],
  "files": [
    "zfhjtwrjsvb8bsbfgjsf9"
  ],
  "labels": {
      "display_name": "Inbox",
      "id": "7hcg****",
      "name": "inbox"
  },
  ...
}

Organize an Inbox With Labels 

Labels are used to categorize and organize messages and threads in a Gmail account. All other email providers use folders to organize inbox content, making Gmail unique in this regard. Unlike folders, a label has a many-to-many relationship with messages and threads, meaning that a message or thread can have any number of labels applied to it, and a label can be applied to any number of messages and threads. Gmail provides system labels for all accounts to denote common types of email, including INBOX, SPAM, DRAFT, STARRED, and IMPORTANT, but Gmail accounts can also have any number of custom labels the user has created.

Nylas exposes Gmail labels via the Labels endpoint, here is an example of what this looks like for a Gmail account. Note the existence of both system and custom labels for the user account:

[
    {
        "account_id": "ez5s7pd20le0tb870zzsmn73",
        "display_name": "Inbox",
        "id": "4mra6by5b7tiwwijs1o5mf2s0",
        "name": "inbox",
        "object": "label"
    },
    {
        "account_id": "ez5s7pd20le0tb870zzsmn73",
        "display_name": "Trash",
        "id": "c1yqipi1a9n3so2rs9ff92cpw",
        "name": "trash",
        "object": "label"
    },
    {
        "account_id": "ez5s7pd20le0tb870zzsmn73",
        "display_name": "My Custom Label",
        "id": "asfgbjgfjg9hgkwdfoa04l408v",
        "name": "my_label",
        "object": "label"
    },
    ...    
]

Then, if you want to apply labels to emails, you can make a PUT requests to the Messages or Threads endpoint, passing the ids for the labels you want to apply.

$ curl -X PUT 'https://api.nylas.com/messages/nbjs8fsj38fjjt0ll7' \
-H 'Authorization: Bearer ACCESS_TOKEN' \
-d '{
           "label_ids": ["asfgbjgfjg9hgkwdfoa04l408v"] 
}'

How to Draft and Send Emails With The Gmail API

Drafts are metadata containers for unsent messages that have the system label DRAFT applied to them; they provide a stable ID for the underlying message they contain. The message contained in a draft behaves like any other message object, except that they can only have the DRAFT system label applied to them. When a draft is sent, Gmail automatically replaces it with a message with the system label SENT.

Here is the process for creating a draft with the Gmail API:

  1. Create a MIME message that complies with RFC 2822
  2. Convert the message to a base64url encoded string
  3. Use the drafts.create method to create a draft, setting the raw message contents to be the encoded string from step 2.

The process to update a draft is very similar: take a base64url encoded MIME message and assign it to be the draft’s message with drafts.update, this will completely replace the content of the draft. If you want to retrieve the contents of the draft, you can use drafts.get with the parameter format=raw. Lastly, the drafts.send method will send a specified draft.

Create Email Drafts With Nylas

With Nylas, drafts are represented as simple JSON, meaning you don’t need to worry about constructing raw MIME content. The Nylas Email API makes it super easy to create and send emails for Gmail accounts with the Send endpoint;

curl -X POST 'https://api.nylas.com/send' -H 'Authorization: Bearer ACCESS_TOKEN' \
-d '{
        "subject": "One Email API to Rule Them All",
        "body": "Keep it secret, keep it safe... Or share it with your friends",
        "from": [{
                "email": "[email protected]",
                "name": "Your Name"
        }],
        "to": [{
                "email": "[email protected]",
                "name": "My Nylas Friend"
        }],
}'

If you want to create a draft without sending it, you can use the Drafts endpoint which uses a nearly identical process to the Send endpoint. Then, when you’re ready to send the draft, you can pass its ID to the Send endpoint:

curl -X POST 'https://api.nylas.com/send' \
-H 'Authorization: Bearer ACCESS_TOKEN' \
-d '{
    "draft_id": "dfgtt63423fsj38fjjt0ll7",
    "version": 0
}'

How to Attach and Upload Files

The Gmail API provides three options to upload media and other certain types of binary data. 

  • Simple upload –   The easiest method  to upload files to Gmail, but it only works for files that are 5 MB or less and it doesn’t let you provide metadata for the file.
  • Multipart upload – Allows quick transfer of smaller files and associated metadata in a single request. This is recommended only for uploads you’re willing to retry if they fail
  • Resumable upload – This is the most reliable upload method because it allows you to resume upload operations if the connection fails. This is particularly useful for larger file transfers, or in situations with unreliable network conditions, such as mobile apps. It also can help reduce bandwidth usage because it doesn’t require you to restart uploads from the start if they fail.

Upload and Attach Files With Nylas

Nylas makes it extremely easy to upload a file for attachments via a POST request to the Files endpoint. 

$ curl -X POST 'https://api.nylas.com/files/' -H 'Authorization: Bearer ACCESS_TOKEN' --form 'file=@my_picture.jpg'
[
    {
        "account_id": "ez5s7pd20lhsfgh5zzsmn73",
        "content_type": "image/jpeg",
        "filename": "picture.jpg",
        "id": "3qz308y87ssdfg554tcizx4",
        "object": "file",
        "size": 2828
    }
]

Once a file has been uploaded to Nylas, you can attach it to drafts by adding the file’s id to the files attribute. You can also embed files directly into the body of the email.

curl -X POST 'https://api.nylas.com/drafts/' \
-H 'Authorization: Bearer ACCESS_TOKEN' \
-d '{ 
    "body":"Keep it secret, keep it safe... Or share it with your friends.",
    "subject": "One Email API to Rule Them All",
    "file_ids": ["3qz308y87ssdfg554tcizx4"]
    "to": [
        {
           {"email": "[email protected]", "name": "My Nylas Friend"}
        }
    ]
}`

How to Search An Inbox

The Gmail API lets you search a user’s inbox for messages with a special query parameter to the messages.list and threads.list function. The q parameter lets you pass the exact same search syntax used in the Gmail web-interface to search a user’s inbox based on information like the date, sender, label, or body content.

Search an Inbox With Nylas

The Nylas Search endpoint exposes this functionality directly and proxies the results Gmail provides.

$ curl -X GET https://api.nylas.com/messages/search?q=Nikola -H 'Authorization: Bearer ACCESS_TOKEN'
[
  {
    "subject": "Incredible Wireless Technology!",
    "body": "Have you heard about cellular technology? I hear some people are using it for wireless phone devices.",
    "from": [
        {
          "name": "Nikola Tesla",
          "email": "[email protected]"
        }
    ],
    ...
  },
  ...
]

Gmail API Webhook Notifications

The Gmail API provides webhook notifications that let your app watch for the creation or deletion of emails or labels in a user’s Gmail inbox. This saves you from being required to regularly poll a user’s inbox for new data. Gmail push notifications are delivered via the Google Cloud Pub/Sub API which provides webhooks that let your app receive updates about changes to Gmail accounts. The first step to setting up Gmail push notifications is to create a Cloud Pub/Sub topic and set up a Cloud Pub/Sub client.

The most important component of Gmail API webhook notifications is the history resource: a collection of recently modified messages in chronological order. This is intended to be a lightweight synchronization method that stores a record of recent changes for a Gmail account. Historical changes are typically available for 7 days, but Google offers no guarantees and states that they sometime might only be available for a few hours. In general, the history resource should only be used for immediate synchronization for changes, if you need to synchronize larger amounts of data for a user account you should make batch requests to the messages.get method.

To monitor for changes to a Gmail account with the history resource, you need to make a watch request to the Gmail API that indicates what type of changes you’d like to monitor for; this request expires after 7 days, so if you need to watch for changes beyond that time period you will need to make additional watch requests. When triggered, the Gmail API will send your app a webhook notification that contains an encoded data payload representing the user’s email address and a historyId value that can be used in a history list request to return the ID for the resource that changed. You can then use this ID to request the message or label that has been changed.

Nylas Webhooks

Nylas provides webhooks that enable you to watch for all new messages that are sent and received for a Gmail account. We handle syncing all changes to the Gmail API so you don’t need to worry about setting up Gmail notifications and renewing watch requests. Here’s what a typical webhook notification from Nylas looks like:

{
  "deltas": [
    {
      "date": 1585154979,
      "object": "email",
      "type": "email.created",
      "object_data": {
        "namespace_id": "8imil0s5m740td8ez7ua8tyfq",
        "account_id": "8imil0s5m740td8ez7ua8tyfq",
        "object": "email",
        "attributes": null,
        "id": "1gsys8wu9mkq89qk465010i5t",
        "metadata": null
      }
    }
  ]
}

Other Gmail API Features

The Gmail API also offers settings endpoints that control how features of Gmail behave for a user, such as POP and IMAP access, email forwarding, filters, vacation auto-response, send-as aliases, signatures, delegates, language, and more.

How Nylas Makes Your Email Integration Simple

The Nylas Platform abstracts away the complexity of integration directly with third party APIs like the Gmail API. Let’s take a look at a few of the ways Nylas makes it super easy to integrate Gmail accounts so you can spend more time on the features your users love.

Who Has Time for MIME Anyways?

To fully integrate with the Gmail API you need to both ingest and create/modify raw MIME content, which can be a fairly significant hassle. Nylas provides all email data in a simple, easy to use JSON format that is well-supported in virtually every programming language. If you absolutely need to use MIME for sending emails, the Nylas Send endpoint has a method for sending emails from raw MIME content.

Nylas Provides More Email Insight

The Gmail notification system only allows you to watch for the creation and deletion of email messages. Nylas also provides this same functionality, but expands upon it by also providing open and click tracking to enable you to get better insight into interactions people have with emails they receive from your users. When this feature is used, your app will receive notifications the first time a recipient interacts with any emails that incorporate this feature.

Gmail API Synchronization is Complicated

If you need to parse large amounts of historical data from a Gmail inbox, or keep tabs on ongoing changes to a user’s Gmail account, you will need to consider what type of synchronization methods you’ll use. For large amounts of data, you’ll need to make batched requests to the messages resource to access all of the data, and then store the relevant data so you can access it when necessary. 

If you need to monitor for ongoing changes to a Gmail user’s inbox, you’ll need to make use of the History resource. The Gmail API offers no guaranteed predictability for this resource, so you will also need to regularly verify data to make sure you don’t miss any important changes. Not to mention, you also need to frequently refresh your watch request to ensure the Gmail API continues to send your app updates. 

The Nylas Sync Engine automatically handles all of this syncing for you and provides filters that let you access only the data you care about the most. Nylas also lets you easily monitor for changes to a user’s inbox via Webhooks that will continue to deliver updates to your app without any further maintenance required. This allows you to focus the features your users love rather than dealing with large amounts of complex user data. 

Take Your Email Integration Further With Nylas

Why Stop with Gmail? Nylas supports 100% of email, calendar, and contacts providers out of the box, enabling your users to keep using their calendar provider of choice. This post has only covered a fraction of the benefits the Nylas Platform provides, let’s take a look at a few of the other reason why you should build your email integration with Nylas.

Related resources

How to customize the Nylas Scheduler workflow with custom events

We’re excited to announce the launch of the Nylas Scheduler v3! Efficient scheduling is essential…

How to block time slots in Outlook and Google calendar with Nylas Calendar API

Key Takeaways Managing calendar availability is essential for professionals, teams, and businesses to stay organized…

How to Solve Webhook Integration Challenges with PubSub Notification Channel

Key Takeaways This article addresses the challenges of webhook integration and introduces the PubSub Notification…