- Products
- Solutions Use casesBy industry
- Developers
- Resources Connect
- Pricing
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.
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.
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.
Messages and labels are the fundamental building blocks of the Gmail API, this section will cover how to work with these resources.
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:
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": "alex@bell.com" }, { "name": "Nikola Tesla", "email": "tesla@wireless.io" } ], ... } ]
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": "tesla@wireless.io" } ], "to": [ { "name": "Alexander Graham Bell", "email": "alex@bell.com" } ], "files": [ "zfhjtwrjsvb8bsbfgjsf9" ], "labels": { "display_name": "Inbox", "id": "7hcg****", "name": "inbox" }, ... }
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"] }'
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:
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.
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": "you@example.com", "name": "Your Name" }], "to": [{ "email": "swag@nylas.com", "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 }'
The Gmail API provides three options to upload media and other certain types of binary data.
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": "swag@nylas.com", "name": "My Nylas Friend"} } ] }`
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.
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": "tesla@wireless.io" } ], ... }, ... ]
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 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 } } ] }
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.
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.
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.
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.
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.
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.
Learn how to create an appointment scheduler in your React app using Nylas Scheduler. Streamline bookings and UX with step-by-step guidance.
Dive into the world of smart Web Components for advanced API integration solutions. Design elegant, customizable elements to elevate user experiences.
Elevate your app’s scheduling with a React calendar component and seamlessly integrate with Nylas for efficient calendar management.
Ben is the Developer Advocate for Nylas. He is a triathlete, musician, avid gamer, and loves to seek out the best breakfast tacos in Austin, Texas.