$ 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:
- Create a MIME message that complies with RFC 2822
- Convert the message to a base64url encoded string
- 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.