NAV
curl ruby python node

Welcome

API Docs

You’re looking at the docs in Ruby mode. All of the examples will be in
context of the Nylas Ruby gem.

You’re looking at the docs in Python mode. All of the examples will be in
context of the Nylas Python library.

You’re looking at the docs in curl mode. All of the examples will be in
context of raw shell API requests using cURL.


Click the tabs above to change the language/platform for the examples.

The Nylas Platform provides a modern API that works with existing email providers. It makes it simple and fast to integrate your app with a user’s email, contacts, or calendar data, and eliminates the complexity of working with old protocols like IMAP and MIME.

The API is designed around the REST ideology, providing simple and predictable URIs to access and modify objects. Requests support standard HTTP methods like GET, PUT, POST, and DELETE and standard status codes. Response bodies are always UTF-8 encoded JSON objects, unless explicitly documented otherwise.

Looking to sync and process mail on-the-fly for many accounts? Check out the Nylas Sync Strategies article in our Knowledge Base for our recommended approach.

Authentication

There are two ways you can connect users to your application. With our native authentication flow, a user never has to leave your application to connect their account and you have the freedom to design what the entire process looks like natively.

If you don’t want to design an authentication flow yourself, you can always use our OAuth flow to get started quicker. Keep in mind this may be faster initially, but you’ll have less control over how the authentication process looks to your user.

Native Authentication

This is a set of endpoints for programmatically creating and updating accounts on Nylas Cloud. It allows you to build a signup form for a user to connect their mailbox to your application.

Connecting a new account is a two-step process, and follows semantics similar to OAuth. The first step is verifying credentials from a user, and the second step is associating this new account with your application in order to receive an API access token.

There are two main endpoints:

https://api.nylas.com/connect/authorize for authenticating a mailbox
https://api.nylas.com/connect/token for connecting the mailbox to your Nylas Cloud app

All API requests must be made over SSL (HTTPS). The Nylas API is not available via unencrypted HTTP.

Before you can interact with the Nylas REST API, you need to sign up for a developer account and create an App ID + Secret pair.

Authorize

This endpoint is where your application sends mailbox credentials to verify they are correct. This begins the connection process.

method POST
endpoint https://api.nylas.com/connect/authorize

Your app should POST a valid JSON body with the following attributes.

attribute description
client_id string, required Your App ID from the Nylas API console.
name string, required The full name of the user. e.g. “John Snow”
email_address string, required The user’s email address
provider string, required One of the Nylas Cloud supported providers. Note that this value will impact the settings your app provides.
settings JSON object, required See below for provider-specific settings
reauth_account_id string id, optional Optional existing account_id to re-authenticate. This is useful if the account has invalid credentials.

Returned Object

A successful authentication will return your application a JSON encoded body with a single code parameter. In the next step, your server backend should exchange this code for an access token, which can then be used to make API requests.

Provider-specific settings

Example Request for a Gmail account

curl -X POST https://api.nylas.com/connect/authorize -d '{ 
        "client_id":     "nylas_client_id",
        "name":          "Erlich Bachman",
        "email_address": "erlich@aviato.com",
        "provider":      "gmail",
        "settings":      {
            "google_client_id":     "google_api_client_id",
            "google_client_secret": "google_api_client_secret",
            "google_refresh_token": "google_api_refresh_token"
        }
      }'

Example Response

{"code": "the response code"}

Gmail / Google Apps additional settings

You need three pieces of information before you can authorize a Google account through Nylas’ APIs. First is the Google client_id and client_secret that you should receive after creating your application in Google’s Developer Console. The final piece is a refresh_token which is what Google will give you after a user approves access to their account. Be sure that you’ve received a long-term refresh_token from Google rather than an access_token, since the access token will expire in an hour.

Ensure that the following scopes are enabled for your application:

https://www.googleapis.com/auth/userinfo.email
https://www.googleapis.com/auth/userinfo.profile
https://mail.google.com/
https://www.google.com/m8/feeds
https://www.googleapis.com/auth/calendar

attribute description
provider string, required Should be set to gmail
settings JSON object, required Google specific settings, see the attributes for this settings JSON object below
Note: See above for other required general attributes

settings JSON object attributes for Google Apps:

attribute description
google_client_id string, required Google API client id. Note: this is a different value from the client_id of your app on the Nylas platform.
google_client_secret string, required Google API client secret
google_refresh_token string, required Google API refresh token

Example Request for an Exchange ActiveSync provider

curl -X POST https://api.nylas.com/connect/authorize -d '{
        "client_id":     "nylas_client_id",
        "name":          "Erlich Bachman",
        "email_address": "erlich@aviato.com",
        "provider":      "eas",
        "settings":      {
             "username": "erlich@aviato.com",
             "password": "makingtheworldabetterplace"
        }
      }'

Example Response

{"code": "the response code"}

Microsoft Exchange ActiveSync additional settings

Nylas Cloud can sync nearly all Exchange accounts. The provider attribute should be set to eas.

The eas_server_host value is optional. If omitted, Nylas Cloud will attempt AutoDiscovery for the server host (endpoint).

attribute description
provider string, required Should be set to eas
settings JSON object, required EAS specific settings, see the attributes for this settings JSON object below
Note: See above for other required general attributes

settings JSON object attributes for EAS:

attribute description
username string, required Username
password string, required Password
eas_server_host string, optional Optional Exchange server endpoint

Example Request for a known IMAP Provider

curl -X POST https://api.nylas.com/connect/authorize -d '{
        "client_id":     "nylas_client_id",
        "name":          "Erlich Bachman",
        "email_address": "erlich@aol.com",
        "provider":      "aol",
        "settings":      {
             "password": "makingtheworldabetterplace"
        }
      }'

Other known IMAP providers

Known providers described in the Nylas Cloud Supported Providers already have hard-coded settings, which means your application only needs to include a password value from the user.

settings JSON object attributes for other IMAP Providers:

attribute description
password string, required Password

Example Request for an IMAP Provider

curl -X POST https://api.nylas.com/connect/authorize -d '{
        "client_id":     "nylas_client_id",
        "name":          "Erlich Bachman",
        "email_address": "erlich@aviato.com",
        "provider":      "imap",
        "settings":      {
            "imap_host":     "imap.aviato.com",
            "imap_port":     12345,
            "imap_username": "erlich.bachman",
            "imap_password": "makingtheworldabetterplace",
            "smtp_host":     "smtp.aviato.net",
            "smtp_port":     12346,
            "smtp_username": "erlich.bachman",
            "smtp_password": "makingtheworldabetterplace",
            "ssl_required":  true
            }
      }'

Regular IMAP / SMTP

Your user can also connect a regular IMAP+SMTP account by specifying the following attributes. Some are optional and default to a standard value.

IMAP and SMTP servers are currently authenticated using username+password based login authentication. If your application needs other authentication mechanisms (such as Kerberos, GSSAPI, or S/KEY) please get in touch with Nylas support.

settings JSON object attributes for regular IMAP

attribute description
imap_host string, required Hostname or IP address of IMAP server. e.g. imap.mycompany.com
imap_port integer, optional Port for IMAP protocol. Defaults to 993 with SSL
imap_username string, required Username to authenticate with IMAP server
imap_password string, required Password to authenticate with IMAP server
smtp_host string, required Hostname or IP address of SMTP server. e.g. smtp.mycompany.com
smtp_port integer, optional Port for SMTP protocol. Defaults to 465 with SSL.
smtp_username string, required Username to authenticate with SMTP server.
smtp_password string, required Password to authenticate with SMTP server.
ssl_required boolean, optional Require SSL when connecting to both SMTP and IMAP. Defaults to true

Get a token

This endpoint is where your application exchanges the code from the previous step and receives an access token. This associates the mailbox with your Nylas Cloud app.

Example Request

  curl -X POST "https://api.nylas.com/connect/token" -d '{
    "client_id": "the-client-id",
    "client_secret": "the-client-secret",
    "code": "the-code"
  }'

Example Response

{
  "account_id": "the-account-id",
  "access_token": "the-token",
  "email_address": "erlich@aviato.com",
  "id": "the-id",
  "name": "Erlich Bachman",
  "object": "account",
  "organization_unit": "folder",
  "provider": "eas",
  "sync_state": "running"
}
method POST
endpoint https://api.nylas.com/connect/token

Your app should POST a valid JSON body with the following attributes.

attribute description
client_id string, required Your App ID from the Nylas API console.
client_secret string, required The client secret from the Nylas API console.
code string, required The value returned in the previous step.

A successful response from this will be an account object with an access_token attribute. Once you’ve obtained a token, you include it with Nylas API requests as the HTTP Basic Auth Username.

You can remove this account from your Nylas Cloud app in the Nylas API console.

OAuth

The Nylas platform uses the OAuth 2.0 protocol for simple, effective authorization. Before making API calls on behalf of a user, you need to fetch an access_token that grants you access to their email. Once you’ve obtained a token, you include it with Nylas API requests as the HTTP Basic Auth Username. Note that although although you’ll immediately have access to the API, it may take some time until all historical messages are synced.

Explicit vs. Implicit OAuth

Nylas supports both two-legged and three-legged OAuth. It’s important to identify which flow you should use:

You should use Server-side (explicit, three-legged) OAuth if you’ll be using the Nylas API from:

You should use Client-side (implicit, two-legged) OAuth if you’ll be using the Nylas API from:

Server Side (Explicit) Flow

The following Python example uses the Flask framework and the Nylas Python SDK.

from flask import Flask, session, request, redirect, url_for
from nylas import APIClient

@app.route('/')
def index():
    redirect_url = "http://0.0.0.0:8888/login_callback"
    client = APIClient(APP_ID, APP_SECRET)
    return redirect(client.authentication_url(redirect_uri))

@app.route('/login_callback')
def login_callback():
    if 'error' in request.args:
        return "Login error: {0}".format(request.args['error'])

    # Exchange the authorization code for an access token
    client = APIClient(APP_ID, APP_SECRET)
    code = request.args.get('code')
    session['access_token'] = client.token_for_code(code)
    return redirect(url_for('subjects'))

# Print the 5 most recent unread message subjects
@app.route('/subjects')
def show_subjects():
    if 'access_token' not in session:
        return redirect(url_for('index'))
    token = session['access_token']
    client = APIClient(APP_ID, APP_SECRET, token)

    subjects = []
    for thread in client.messages.where(unread=True, limit=5):
        subjects.append(thread.subject)
    return '\n'.join(subjects)

The following Ruby example uses Sinatra and the Nylas Ruby SDK.

require 'yaml'
require 'nylas'
require 'sinatra'

# Enable session to store token
enable :sessions
set :session_secret, 'my_super_secret_code'

# Load secrets from config file
config = YAML.load_file('config.yml')

# This URL must be registered with your application in the developer portal
CALLBACK_URL = config["nylas_callback_url"]
APP_ID = config["nylas_app_id"]
APP_SECRET = config["nylas_app_secret"]

# Check app configuration before starting
if APP_ID == 'YOUR_APP_ID' or APP_SECRET == 'YOUR_APP_SECRET'
    raise "You need to configure your app id and secrets in config.yml"
end

def login
    nylas = Nylas::API.new(APP_ID, APP_SECRET, nil)
    nylas.url_for_authentication(CALLBACK_URL, nil)
end

def get_token
    nylas = Nylas::API.new(APP_ID, APP_SECRET, nil)
    nylas.token_for_code(params[:code])
end

get '/' do
    # Redirect to login if session doesn't have an access token
    redirect to(login) unless session[:nylas_token]

    # Get the first namespace
    nylas = Nylas::API.new(APP_ID, APP_SECRET, session[:nylas_token])
    namespace = nylas.first

    # Get the first five unread threads
    recent_emails = []
    nylas.threads.where(:tag => 'unread').range(0,5).each do |thread|
      recent_emails.push(thread.subject)
    end

    # List messages on the first thread
    body = "Hello #{namespace.name}, here are your last 5 emails:\n<br><br>"
    body += "#{recent_emails.join('<br>')}"

    body
end

get '/login_callback' do
    # get token from code
    nylas_token = get_token

    if nylas_token
        # Store token in a session
        session[:nylas_token] = nylas_token
        redirect to('/')
    end

    "Error during auth"
end

Step 1

From your application, redirect users to https://api.nylas.com/oauth/authorize, with the parameters below in the URL query string:

URL Parameter Description
client_id Your Nylas App ID
response_type Set to code
scope Set to email
login_hint The user’s email address, if known
redirect_uri The URI to which the user will be redirected once authentication completes. This must match a URI registered in the developer dashboard.
state Optional arbitrary string that is returned as a URL parameter in your redirect_uri. You can pass a value here to keep track of a specific user’s authentication flow. Also may be used to protect against CSRF attacks

Step 2

Nylas will present your user with the correct sign in panel based on their email address. For example, a user with a Gmail address will see the Gmail “Authorize this Application” screen, while a user with a Yahoo address is shown a Yahoo sign in panel.

If (and only if) Nylas cannot auto detect the user’s email provider from their address, the user will see a provider selection screen first.

For Exchange users, clicking ‘Advanced Settings’ will enable the user to enter a logon name and/or Exchange server. The majority of Exchange users can log on with their email address and auto-detected server details, but some will have to enter this additional information. See the Exchange section for more details.

Step 3

Once the user has signed in, their browser will be redirected to the redirect_uri you provided. If authentication was successful, Nylas will include a code parameter in the query string.

Make an HTTP POST to https://api.nylas.com/oauth/token to exchange the code for an access token. The POST body parameters should include:

Attribute Description
client_id string Your Nylas App ID
client_secret string Your Nylas client secret
grant_type string Set to "authorization_code"
code string The authorization code returned in the previous step

Step 4

You’re done! The response to this request is a JSON object with the following values. Make sure to securely store the access_token and provide it as the HTTP Basic Auth Username to make API calls on behalf of the user.

Attribute Description
access_token string A credential to access data for this account. You should treat this as a long-lived revokable password..
email_address string Canonicalized email address of the account.
provider string Which provider backs the account, e.g. gmail or eas. See Supported providers for a full list.
account_id string Nylas Platform Account ID

Client Side (Implicit) Flow

Step 1

From your application, redirect users to https://api.nylas.com/oauth/authorize, with the parameters below in the URL query string:

URL Parameter Description
client_id Your Nylas App ID
response_type Set to token
scope Set to email
login_hint The user’s email address, if known
redirect_uri The URI to which the user will be redirected once authentication completes. This must match a URI registered in the developer dashboard.
state Optional arbitrary string that is returned as a URL parameter in your redirect_uri. You can pass a value here to keep track of a specific user’s authentication flow. Also may be used to protect against CSRF attacks

Step 2

Nylas will present your user with the correct sign in flow based on their email address. ( Identical to step 2 in ‘Server-side (Explicit) Flow’ above).

Step 3

Once the user has signed in, their browser will be redirected to the redirect_uri you provided. If authentication was successful, Nylas will include a token parameter in the query string.

Step 4

You’re done! We recommend storing the access_token and then removing it from the URL fragment with JavaScript. This is the token you will provide as a HTTP Basic Auth Username to make API calls on behalf of the user.

Authorization Errors

In some scenarios, authentication can fail and you need to display an error message to the user. In these cases, Nylas will include additional parameters when calling your redirect_uri. After presenting the error, you should restart the authorization process.

Attribute Description
error string access_denied, or another error type
reason string A more detailed explanation of the error you may be presented to the end user.

Revoking Tokens

Revoking a token

curl -X POST https://api.nylas.com/oauth/revoke \
    --user ACCESS_TOKEN_TO_REVOKE:

You can easily revoke an access token by issuing a POST request to the following endpoint. Include the to-be-revoked access token as the HTTP Basic Auth username.

method POST
endpoints https://api.nylas.com/oauth/revoke
authentication Access Token as HTTP Basic Auth username

A 200 status code response with an empty body signifies that the token has been successfully revoked and can no longer be used.

Reauthentication



When a user’s credentials or server settings (for IMAP/ SMTP or Exchange) changes, the account will stop syncing and its status will change to ‘invalid-credentials’. For the account sync to resume, you must ask the user to go through the authentication flow again with their new credentials or server settings.

For a credentials change, once the user has reauthenticated, account sync simply resumes.

For a server settings change – for example, if the user changes the IMAP/ SMTP or Exchange server endpoint – all previously synced Nylas API IDs for the account will be invalidated. The user will be associated with a new account and account_id, and the Nylas API token returned from reauthentication will point to this account.
Your application must detect this new account_id and take appropriate measures to invalidate any existing IDs you have cached.

Accounts

An account corresponds to an email address, mailbox, and optionally a calendar. When connecting to the Nylas API, a specific access token gives you access to a specific account’s data.

The account object

Example Request

curl https://api.nylas.com/account -u YOUR_ACCESS_TOKEN:

Example Response

{
    "id": "awa6ltos76vz5hvphkp8k17nt",
    "account_id": "awa6ltos76vz5hvphkp8k17nt",
    "object": "account",
    "name": "Ben Bitdiddle",
    "email_address": "benbitdiddle@gmail.com",
    "provider": "gmail",
    "organization_unit": "label"
}

Example Request

account = nylas.account
puts account.email_address

Example Response

helena.handbasket@nylas.com

An access token can be used to request information about the account it corresponds to. This includes information such as the end-user’s name, email address, and backend mailbox provider. For information about the sync status of an account, see sync status.

method GET
endpoint https://api.nylas.com/account
authentication Access Token as HTTP Basic Auth username

Responses are encoded as UTF-8 JSON objects with the following attributes.

attribute description
id string Globally unique object identifier
object string A string describing the type of object (value is “acount”)
account_id string Reference to parent account object (self-referential in this case)
name string Full name of the user, used as the default “from” name when sending mail.
email_address string The canonical email address of the account. For Gmail accounts, this removes periods and plus suffixes.
provider string Which provider backs the account, e.g. gmail or eas. See Supported providers for a full list.
organization_unit string Either "label" or "folder" depending on the provider capabilities
sync_state string The syncing status of the account. See the sync status documentation for possible values.

Folders vs. Labels

Check if an account uses folders or labels

print account.organization_unit
assert account.has_labels()

Response

label

Check if an account uses folders or labels

puts account.organization_unit

Response

label

Check if an account uses folders or labels

curl https://api.nylas.com/account

Response

{
    "id": "awa6ltos76vz5hvphkp8k17nt",
    "account_id": "awa6ltos76vz5hvphkp8k17nt",
    "object": "account",
    "name": "Ben Bitdiddle",
    "email_address": "benbitdiddle@gmail.com",
    "provider": "gmail",
    "organization_unit": "label",
    "sync_state": "running"
}

Note the organization_unit parameter, which can either be "label" or "folder".

Messages and threads in accounts can either be organized around folders, or around labels. This depends on the backend provider. For example, Gmail uses labels whereas Yahoo! Mail users folders.

Labels and folders have fundamentally different semantics and these are preserved in the API. The core difference is that a message can have more than one label, versus only having one folder.

The organization_unit attribute on the account object indicates whether the account supports folders or labels. Possible values are folder or label. For more details on format and usage, see the related documentation on Folders and Labels.

Account Management

These endpoints allow for account management outside the developer console interface. You can list, cancel, and reactivate accounts associated with your application.

Listing All Accounts

Example Request

curl -X GET -u YOUR_APP_SECRET https://api.nylas.com/a/YOUR_APP_ID/accounts

Example Response

[
  {
    "account_id": "622x1k5v1ujh55t6ucel7av4",
    "billing_state": "free",
    "id": "622x1k5v1ujh55t6ucel7av4",
    "sync_state": "running"
  },
  {
    "account_id": "123rvgm1iccsgnjj7nn6jwu1",
    "billing_state": "paid",
    "id": "123rvgm1iccsgnjj7nn6jwu1",
    "sync_state": "running"
  }
]

Note the id and account_id attributes are equivalent to the same attributes on the https://api.nylas.com/account endpoint for a connected account.

You can access the /accounts endpoint within your application namespace. This will list the accounts associated with your app.

Instead of using a connected email account’s token, you use your App Secret for the Basic Auth username which can be found in the developer console.

Often you may want to retrieve a list of all users who have connected to your application. Note this endpoint uses the management API domain with different authentication.

Method GET
Endpoint https://api.nylas.com/a/YOUR_APP_ID/accounts
Authentication App Secret Key passed as HTTP Basic Auth username

Responses are encoded as UTF-8 JSON objects with the following attributes.

attribute description
account_id string Reference to parent account object (self-referential in this case)
billing_state string The billing state for the account. Can be free, paid, cancelled, or deleted
id string Globally unique object identifier
sync_state string The current sync state for the account. See all sync states
Method GET
Endpoint https://api.nylas.com/a/YOUR_APP_ID/accounts/:id
Authentication App Secret Key passed as HTTP Basic Auth username

Cancelling an account

You can cancel paid accounts by using this endpoint.

Example Request

curl -X POST -u YOUR_APP_SECRET https://api.nylas.com/a/YOUR_APP_ID/accounts/ID/downgrade

Example Request

nylas = Nylas::API.new(config.nylas_app_id, config.nylas_app_secret, nil)  
account =  nylas.accounts.find(account_id)
account.downgrade!

Example Response

{ "success": "true" }
Method POST
Endpoint https://api.nylas.com/a/YOUR_APP_ID/accounts/:id/downgrade
Authentication App Secret Key passed as HTTP Basic Auth username

Example Request

curl -X POST -u YOUR_APP_SECRET https://api.nylas.com/a/YOUR_APP_ID/accounts/ID/upgrade

Example Request

nylas = Nylas::API.new(config.nylas_app_id, config.nylas_app_secret, nil)  
account =  nylas.accounts.find(account_id)
account.upgrade!

Example Response

{ "success": "true" }

Reactivating accounts

You can re-enable cancelled accounts to make them active again using this endpoint.

Method POST
Endpoint https://api.nylas.com/a/YOUR_APP_ID/accounts/:id/upgrade
Authentication App Secret Key passed as HTTP Basic Auth username

Deleting accounts

If you would like for an account’s data to be completely removed from Nylas’ servers, follow these steps to queue the account for deletion:

  1. Revoke the account’s access token
  2. Cancel the account.

Please note once you follow these steps, the account will be queued for deletion. It can take up to 30 days for an account’s data to be completely removed. Furthermore, if the user re-connects their account and authenticates again, their account won’t be deleted.

Threads

Threads are a first-class object, allowing you to build beautiful mail applications that behave the way users have come to expect. Actions like archiving or deleting can be performed on threads or individual messages.

Nylas threads messages together using a variety of heuristics. On Gmail and Microsoft Exchange accounts, messages will be threaded together as close as possible to the representation in those environments. For all other providers (including generic IMAP), messages are threaded using a custom JWZ-inspired algorithm. (Open source here, for the curious.)

The thread object

Example Request

curl https://api.nylas.com/threads

Example Response

{
    "id": "evh5uy0shhpm5d0le89goor17",
    "object": "thread",
    "account_id": "awa6ltos76vz5hvphkp8k17nt",
    "subject": "Dinner Party on Friday",
    "unread": false,
    "starred": false,
    "last_message_timestamp": 1398229259,
    "last_message_received_timestamp": 1398229259,
    "first_message_timestamp": 1298229259,
    "participants": [
        {
            "name": "Ben Bitdiddle",
            "email": "ben.bitdiddle@gmail.com"
        },
        {
            "name": "",
            "email": "cmason@cmu.edu"
        },
        {
            "name": "Bill Rogers",
            "email": "wrogers@mit.edu"
        },
        {
            "name": "Nylas Support (Kevin)",
            "email": "support@example.com"
        },
        {
            "name": "Nylas Support (James)",
            "email": "support@example.com"
        }
    ],
    "snippet": "Hey Bill, Looking forward to getting together for dinner on Friday. What can I bring? I have a couple bottles of wine or could put together",
    "folders": [
        {
            "name": "inbox",
            "display_name": "INBOX",
            "id": "f0idlvozkrpj3ihxze7obpivh"
        },
    ],
    "message_ids": [
        "251r594smznew6yhiocht2v29",
        "7upzl8ss738iz8xf48lm84q3e",
        "ah5wuphj3t83j260jqucm9a28"
    ],
    "draft_ids": [
        "251r594smznew6yhi12312saq"
    ],
    "version": 2
}

Python Example

client = APIClient(APP_ID, APP_SECRET, token)
account = client.accounts

# Fetch the first thread
thread = account.threads.first()

# Fetch a specific thread
thread = account.threads.find('ac123acd123ef123')

# List all threads tagged `inbox`
# (paginating 50 at a time until no more are returned.)
for thread in account.threads.items():
    print thread.subject

# List the 5 most recent unread threads
for thread in account.threads.where(unread=True, limit=5):
    print thread.subject

# List starred threads
for thread in account.threads.where(starred=True):
    print thread.subject

# List all threads with 'ben@nylas.com'
for thread in account.threads.where(any_email='ben@nylas.com').items():
    print thread.subject

Ruby Example

nylas = Nylas::API.new(APP_ID, APP_SECRET, token)

# Fetch the first thread
thread = nylas.threads.first

# Fetch a specific thread
thread = nylas.threads.find('ac123acd123ef123')

# List all threads tagged `inbox`
# (paginating 50 at a time until no more are returned.)
nylas.threads.where(:in => 'inbox').each do |thread|
    puts thread.subject
end

# List the 5 most recent unread threads
nylas.threads.where(:unread => true, :limit => 5).each do |thread|
    puts thread.subject
end

# List starred threads
nylas.threads.where(:starred => true).each do |thread|
    puts thread.subject
end

# List all threads with 'ben@nylas.com'
nylas.threads.where(:any_email => 'ben@nylas.com').each do |thread|
    puts thread.subject
end

Threads are container objects for messages. All messages are part of a thread, even if that thread has one message only. The thread APIs support either pagination through all threads, or requesting a single specific thread object.

method GET
endpoints https://api.nylas.com/threads
https://api.nylas.com/threads/:id
authentication Access Token as HTTP Basic Auth username

Responses are encoded as UTF-8 JSON objects with the following attributes:

attribute description
idstring Globally unique object identifier
objectstring A string describing the type of object (value is “thread”)
account_idstring Reference to parent account object
subjectstring Subject of the first message in the thread
unreadboolean Indicates whether the thread contains unread messages (mutable)
starredboolean Indicates one or more messages are starred, aka flagged (mutable)
last_message_timestampunix timestamp Timestamp of the most recent message
last_message_received_timestampunix timestamp Timestamp of the most recently received message.
(Excludes messages sent by the account.)
first_message_timestampunix timestamp Timestamp when the thread began
participantsarray List of participant objects computed from all messages in the thread.
snippetstring A shortened plain-text preview of the most recent message in the thread
message_idsarray Array of IDs for messages within the thread, sorted by their timestamps
draft_idsarray Array of IDs for unsent drafts in the thread. May be null or absent
versioninteger Incrementing value related to thread updates.
You can use this to compare revisions, or invalidate your local cache.
foldersarray The folder location(s) of a thread, present only if the parent account’s organization_unit is folder. Note that threads can span folders, depending on the location of the thread’s messages. See the folders docs for more info.
labelsarray A list of label objects, present only if the parent account’s organization_unit is label. These have Gmail-style semantics and can be arbitrarily added and removed from threads.

To load all messages for a given thread, you should instead use the messages endpoint with a thread_id filter parameter.

Filtering

Example Requests

All threads in the inbox:

curl https://api.nylas.com/threads?in=inbox

All unread threads that include mark@nylas.com as a participant, sorted by most recent (default).

curl "https://api.nylas.com/threads?unread=true&any_email=mark@nylas.com"

Example Requests

All threads in the inbox:

inbox_threads = nylas.threads.where(:in => 'inbox')

All unread threads that include mark@nylas.com as a participant, sorted by most recent (default).

unread_w_mark = nylas.threads.where(:unread => true, :any_email => 'mark@nylas.com')

The threads endpoint supports filters, making it easy to return a subset of threads in specific folder, from an address, with a specific subject, etc.

URL Parameter Description
subject string Return threads with a matching literal subject
any_email email address Return threads that have been sent or received from this email address
to email address Return threads containing messages sent to this email address
from email address Return threads containing messages sent from this email address
cc email address Return threads containing messages that were CC’d to this email address
bcc email address Return threads containing messages that were BCC’d to this email address, likely sent from the parent account. (Most SMTP gateways remove BCC information.)
in folder or label Return threads in a given folder, or with a given label. This parameter supports the name, display_name, or id of a folder or label. Note: If you’d like to get all drafts use the drafts endpoint.
unread boolean Return threads with one or more unread messages
starred boolean Return threads with one or more starred messages
filename string Return threads that contain attachments with the given filename
last_message_before unix timestamp Return threads whose most recent message was received before this timestamp
last_message_after unix timestamp Return threads whose most recent message was received after this timestamp
started_before unix timestamp Return threads whose first message was received before this timestamp
started_after unix timestamp Return threads whose first message was received after this timestamp.

Pagination

curl "https://api.nylas.com/threads?limit=20&offset=460"

By default the /threads endpoint will return a maximum of 100 objects. You can paginate through an entire user’s mailbox by using the limit and offset URL parameters. See Pagination for more details.

An operation on a thread is performed on all the messages in the thread. It’s a convenient shortcut to perform bulk operations on messages, which is what users have come to expect with modern mail applications. Below are a list of the operations you can perform on a thread.

Unread status

The unread attribute is set to true if any of the thread’s messages are unread. To mark all underlying messages as “read”, your application should change the unread attribute to false on the thread. Any change to a thread’s unread status will cascade to all messages in the thread.

Changes to the unread status will propagate to the backend mailbox provider, such as Gmail or Exchange.

Mark a thread as unread

curl -X PUT https://api.nylas.com/threads/evh5uy0shhpm5d0le89goor17 \
    -d '{"unread": false}'

Mark a thread as read

thread.mark_as_read()

Mark a thread as read

thread.unread = false
thread.save!
method PUT
endpoint https://api.nylas.com/threads/:id
authentication Access Token as HTTP Basic Auth username
request body JSON-encoded attribute-value pairs

Specify the following attributes as a JSON-encoded object in the request body.

Attribute Description
unread boolean Set true to mark as unread, and false to mark as read

Starring (flags)

Stars—also know as “flags”—are displayed in nearly every mail app, and are an easy way to highlight a specific message. Although most apps usually show stars at the thread level, they are actually an attribute of messages themselves. Changing the starred property of a thread will cause all messages in that thread to be starred or unstarred.

The starred property in the Nylas API is equivalent to stars in Gmail, the IMAP flagged message attribute and Microsoft Exchange message “flags.”

Changes to the starred value will propagate to the backend mailbox provider, such as Gmail or Exchange.

Star a thread

curl -X PUT https://api.nylas.com/threads/evh5uy0shhpm5d0le89goor17 \
    -d '{"starred": true}'

Star a thread

thread.star()

Star a thread

thread.starred = true
thread.save!
method PUT
endpoint https://api.nylas.com/threads/:id
authentication Access Token as HTTP Basic Auth username
request body JSON-encoded attribute-value pairs

Specify the following attributes as a JSON-encoded object in the request body.

Attribute Description
starred boolean Set true to star, and false to un-star a thread

Moving a thread

Note: this is only supported for accounts where the organization_unit is set to folder. Generally this is all non-Gmail/Google Apps accounts.You can check if an account supports folders by the organization_unit property on the account object.

The folders attribute of a thread contains an array of folder objects. This is the union of all folders containing messages in the thread. For example, an ongoing discussion thread would likely have messages in the Inbox, Sent Mail, and perhaps the Archive folders.

Your application can move a thread to a new folder by specifying a folder_id, and this will perform the operation on all messages within that thread. Using the Inbox folder ID will move all messages of the thread to the Inbox. Note that nessages in the sent folder are not moved via this batch action.

Moving a thread to a folder

curl -X PUT https://api.nylas.com/threads/evh5uy0shhpm5d0le89goor17 \
    -d '{"folder_id": "pgvihjvuptbwv57kiz624zv7"}'

Moving a thread to a folder

Moving a thread to a folder

trash_id = 'ds36ik7o55gdqlvpbrjbg9ovn'
thread.update_folder(trash_id)

Moving a thread to a folder

Moving a thread to a folder

trash_id = 'ds36ik7o55gdqlvpbrjbg9ovn'
thread.folder = trash_id
thread.save!
method PUT
endpoint https://api.nylas.com/threads/:id
authentication Access Token as HTTP Basic Auth username
request body JSON-encoded attribute-value pairs

Specify the following attributes as a JSON-encoded object in the request body.

Attribute Description
folder_id string ID of folder to move this thread to

This message move will propagate to the backend mailbox provider (such as Yahoo! Mail).

Adding or removing labels

Note: this is only supported for accounts where the organization_unit is set to label. Generally this is only Gmail/Google Apps accounts.

Labels are a Gmail-specific way of organizing messages. A message or thread can have multiple labels, enabling more complex queries and email management workflows. The labels attribute of a thread contains an array of label objects. This is the union of all labels on messages in the thread.

The Nylas platform lets you easily change the labels associated with a message. This change will propagate to the backend mailbox provider (Gmail).

Modifying labels

curl -X PUT https://api.nylas.com/threads/evh5uy0shhpm5d0le89goor17 \
    -d '{"label_ids": ["4zv7pgvihjvuptbwv57kiz62", "76zrfd8ln5zo2swalu1yojhty"]}'

Removing one of the labels

curl -X PUT https://api.nylas.com/threads/evh5uy0shhpm5d0le89goor17 \
    -d '{"label_ids": ["4zv7pgvihjvuptbwv57kiz62"]}'

Modifying labels

# Works on messages or threads
label_ids = ['4zv7pgvihjvuptbwv57kiz62', '76zrfd8ln5zo2swalu1yojhty']
thread.update_labels(label_ids)

Removing one of the labels

important_id = 'aw6p0mya6v3r96vyj8kooxa5v'
thread.remove_label(important_id)

Modifying labels

label_ids = ['4zv7pgvihjvuptbwv57kiz62', '76zrfd8ln5zo2swalu1yojhty']
thread.labels = labels_ids
thread.save!

Removing one of the labels

important_id = 'aw6p0mya6v3r96vyj8kooxa5v'
thread.labels.delete(important_id)
thread.save!
method PUT
endpoint https://api.nylas.com/threads/:id
authentication Access Token as HTTP Basic Auth username
request body JSON-encoded attribute-value pairs

Specify the following attributes as a JSON-encoded object in the request body.

Attribute Description
label_ids array Array of label IDs to apply, overwriting all previous labels on the thread.

Note that the array of label IDs specified will overwrite all previous labels. When making label modifications, we strongly suggest that your application fetch the latest message object before applying changes in order to not accidentally remove labels the user has applied.

Modifying labels and folders can be performed at the message level as well, although this has the same effect in many mail applications. See the Messages documentation for more details.

Expanded Threads View

Example Request

curl https://api.nylas.com/threads?view=expanded

Expands threads response to contain message/draft sub-objects. Adding view=expanded will remove message_ids and draft_ids, and include messages and drafts. Note the message and draft sub-objects do not include a body parameter.

Messages

Messages are the fundamental object of the Nylas platform, and the core building block for most email applications. They contain several pieces of information, such as when a message was sent, the sender’s address, to whom it was sent, and the message body. They can also contain files (attachments), calendar event invitations, and more.

The message object

Example Request

curl https://api.nylas.com/messages/awa6ltos76vz5hvphkp8k17nt

Response

{
    "id": "84umizq7c4jtrew491brpa6iu",
    "object": "message",
    "account_id": "14e5bn96uizyuhidhcw5rfrb0",
    "thread_id": "5vryyrki4fqt7am31uso27t3f",
    "subject": "Re: Dinner on Friday?",
    "from": [
        {
            "name": "Ben Bitdiddle",
            "email": "ben.bitdiddle@gmail.com"
        }
    ],
    "to": [
        {
            "name": "Bill Rogers",
            "email": "wbrogers@mit.edu"
        }
    ],
    "cc": [],
    "bcc": [],
    "reply_to": [],
    "date": 1370084645,
    "unread": true,
    "starred": false,
    "folder": {
        "name": "inbox",
        "display_name": "INBOX",
        "id": "f0idlvozkrpj3ihxze7obpivh"
    },
    "snippet": "Sounds good--that bottle of Pinot should go well with the meal. I'll also bring a surprise for dessert. :) Do you have ice cream? Looking fo",
    "body": "<html><body>....</body></html>",
    "files": [
        {
            "content_type": "image/jpeg",
            "filename": "walter.jpg",
            "id": "7jm8bplrg5tx0c7pon56tx30r",
            "size": 38633,
            "content_id": "ii_i2cg7byn1_1499bfd99727e569"
        }
    ],
    "events": [
        {
            "object": "event",
            "id": "4ee4xbnx7pxdb9g7c2f8ncyto",
            "calendar_id": "ci0k1wfyv533ccgox4t7uri4h",
            "account_id": "14e5bn96uizyuhidhcw5rfrb0",
            "description": null,
            "location": null,
            "participants": [
                {
                    "email": "example@gmail.com",
                    "name": "Ben Bitdiddle",
                    "status": "yes"
                }
            ],
            "read_only": false,
            "title": "Meeting with Ben Bitdiddle",
            "when": {
                "object": "timespan",
                "end_time": 1408123800,
                "start_time": 1408120200
            },
            "busy": true,
            "status": "confirmed"
        }
    ]
}

Example Request

msg = nylas.messages.find('awa6ltos76vz5hvphkp8k17nt')
puts msg.snippet

Response
Sounds good–that bottle of Pinot should go well with the meal. I’ll also bring a surprise for dessert. :) Do you have ice cream? Looking fo

The Nylas APIs expose a parsed and sanitized version of the original rfc-2822 email object, combined with state from the mail server, such as unread status and folder location. This results in a simple and universal object type that makes building applications a breeze.

method GET
endpoints https://api.nylas.com/messages
https://api.nylas.com/messages/:id
authentication Access Token as HTTP Basic Auth username

Responses are encoded as UTF-8 JSON objects with the following attributes:

Attribute Description
idstring Globally unique object identifier
objectstring A string describing the type of object (value is “message”)
account_idstring Reference to parent account object
thread_idstring Reference to parent thread object (all messages have a thread)
subjectstring Subject line of the message
fromarray List of name+email pairs the message was sent from. This is usually one object, but can be many.
toarray Array of name+email pairs the message was sent to.
ccarray Array of name+email pairs the message was cc’d to.
bccarray Array of name+email pairs the message was bcc’d to. In received mail this is nearly always empty (for obvious reasons).
reply_toarray Array of name+email pairs replies should be sent to.
dateunix timestamp Timestamp of the date the message was received by the mail server. Note this may be different from the unverified Date header in raw message object.
unreadboolean Message is unread, default for new incoming mail (mutable)
starred boolean Starred or flagged state (mutable)
snippet string A shortened plain-text preview of the message body
body string The full HTML message body. Messages with only plain-text representations are up-converted to HTML.
files array Array of file objects, if message includes attachments
events array Array event objects, if message includes calendar invites
folderfolder object A single folder object indicating the location of the message, present only if the parent account’s organization_unit is folder. This property can be changed to move the message to different folder.
labelsarray An list of label objects, present only if the parent account’s organization_unit is "label". These have Gmail-style semantics and can be arbitrarily added and removed from messages.

Note that although message bodies are HTML, they are generally not safe to directly inject into a web app. This could result in global styles being applied to your app, or the execution of arbitrary JavaScript.

Using filters

Request all messages in the Inbox

curl https://api.nylas.com/messages?in=inbox

Request all messages in a particular thread

curl https://api.nylas.com/messages?thread_id=aqb0llc2ioo0bclh7uxkim9z6

Request all messags from no-reply@asana.com

curl https://api.nylas.com/messages?from=no-reply@asana.com

Request messages that have an attachment named image.jpg

curl https://api.nylas.com/messages?filename=image.jpg

Request all messages in the Inbox

messages = nylas.messages.where(:in => 'inbox')

Request all messages in a particular thread

messages = nylas.messages.where(:thread_id => 'aqb0llc2ioo0bclh7uxkim9z6')

Request all messags from no-reply@asana.com

messages = nylas.messages.where(:from => 'no-reply@asana.com')

Request messages that have an attachment named image.jpg

messages = nylas.messages.where(:filename => 'image.jpg')

The messages endpoint supports filters, making it easy to return a subset of messages in specific folder, from an address, with a specific subject, etc.

One particularly useful filter parameter is thread_id, which can return all messages belonging to a specific thread.

URL Parameter Description
subject string Return messages with a matching literal subject
any_email email address Return messages that have been sent or received from this email address
to email address Return messages sent to this email address
from email address Return messages sent from this email address
cc email address Return messages that were CC’d to this email address
bcc email address Return messages that were BCC’d to this email address, likely sent from the parent account. (Most SMTP gateways remove BCC information.)
in folder or label Return messages in a given folder, or with a given label. This parameter supports the name, display_name, or id of a folder or label. Note: If you’d like to get all drafts use the drafts endpoint.
unread boolean Return messages that are unread (or not)
starred boolean Return messages that are starred (or not)
filename string Return messages that contain an attachment with the given filename
thread_idstring Return all messages belonging to a specific thread
received_before unix timestamp Return messages received before this timestamp
received_after unix timestamp Return messages received after this timestamp

Unread status

In most systems, incoming mail is given an “unread” status to help the user triage messages. When viewing a message, it’s customary for a mail app to automatically modify this “unread” attribute and remove the notification or highlight.

However—unlike its literal meaning—the unread value is mutable, and so it’s possible to manually change a message back to “unread.” Users will often do this as a reminder to follow up or triage a message later.

The Nylas platform lets you easily change the unread property of a message. This change will propagate to the backend mailbox provider, such as Gmail or Exchange.

Marking a message as read

curl -X PUT https://api.nylas.com/messages/84umizq7c4jtrew491brpa6iu \
    -H "Content-Type: application/json" \
    -d '{"unread": false}'

Marking a message as read

msg = nylas.messages.first
msg.unread = false
msg.save!
method PUT
endpoint https://api.nylas.com/messages/:id
authentication Access Token as HTTP Basic Auth username
request body JSON-encoded attribute-value pairs

Specify the following attributes as a JSON-encoded object in the request body.

Attribute Description
unread boolean Set true to mark as unread, and false to mark as read

Starring (flags)

Stars—also know as “flags”—are displayed in nearly every mail app, and are an easy way to highlight a specific message. Although most apps usually show stars at the thread level, they are actually an attribute of messages themselves. (e.g. If one message in a thread is starred, the entire thread is shown as starred.)

The starred property in the Nylas API is equivalent to stars in Gmail, the IMAP flagged message attribute and Microsoft Exchange message “flags.”

They Nylas platform lets you easily change the starred property of a message. This change will propagate to the backend mailbox provider, such as Gmail or Exchange.

Starring a message

curl -X PUT https://api.nylas.com/messages/84umizq7c4jtrew491brpa6iu \
    -H "Content-Type: application/json" \
    -d '{"starred": true}'

Starring a message

msg = nylas.messages.first
msg.starred = true
msg.save!
method PUT
endpoint https://api.nylas.com/messages/:id
authentication Access Token as HTTP Basic Auth username
request body JSON-encoded attribute-value pairs

Specify the following attributes as a JSON-encoded object in the request body.

Attribute Description
starred boolean Set true to star, and false to un-star a message

Moving a message

Note: this is only supported for accounts where the organization_unit is set to folder. Generally this is all non-Gmail/Google Apps accounts.

Folders are a common way to organize email messages. A mailbox usually has a set of standard folders like Inbox, Sent Mail, and Trash, along with any number of user-created folders. For more information about types and capabilities, see the Folders section.

Nylas supports moving messages between folders with a single, simple API call. Note that messages can only exist within one folder.

Moving a message to a folder

curl -X PUT https://api.nylas.com/messages/84umizq7c4jtrew491brpa6iu \
    -d '{"folder_id": "pgvihjvuptbwv57kiz624zv7"}'

Moving a message to a folder

Moving a message to a folder

trash_id = 'ds36ik7o55gdqlvpbrjbg9ovn'
message.update_folder(trash_id)

Moving a message to a folder

Moving a message to a folder

trash_id = 'ds36ik7o55gdqlvpbrjbg9ovn'
message.folder = trash_id
message.save!
method PUT
endpoint https://api.nylas.com/messages/:id
authentication Access Token as HTTP Basic Auth username
request body JSON-encoded attribute-value pairs

Specify the following attributes as a JSON-encoded object in the request body.

Attribute Description
folder_id string ID of folder to move this message to

This message move will propagate to the backend mailbox provider (such as Yahoo! Mail).

Adding or removing labels

Note: this is only supported for accounts where the organization_unit is set to label. Generally this is only Gmail/Google Apps accounts.

Labels are a Gmail-specific way of organizing messages. A message or thread can have multiple labels, enabling more complex queries and email management workflows.

The Nylas platform lets you easily change the labels associated with a message. This change will propagate to the backend mailbox provider (Gmail).

Modifying labels

curl -X PUT https://api.nylas.com/messages/84umizq7c4jtrew491brpa6iu \
    -d '{"label_ids": ["4zv7pgvihjvuptbwv57kiz62", "76zrfd8ln5zo2swalu1yojhty"]}'

Removing one of the labels

curl -X PUT https://api.nylas.com/messages/84umizq7c4jtrew491brpa6iu \
    -d '{"label_ids": ["4zv7pgvihjvuptbwv57kiz62"]}'

Modifying labels

Modifying labels

# Works on messages or threads
label_ids = ['4zv7pgvihjvuptbwv57kiz62', '76zrfd8ln5zo2swalu1yojhty']
message.update_labels(label_ids)
thread.update_labels(label_ids)

Removing one of the labels

important_id = 'aw6p0mya6v3r96vyj8kooxa5v'
message.remove_label(important_id)

Modifying labels

Modifying labels

# Works on messages or threads
label_ids = ['4zv7pgvihjvuptbwv57kiz62', '76zrfd8ln5zo2swalu1yojhty']
message.labels = labels_ids
message.save!

thread.labels = labels_ids
thread.save!

Removing one of the labels

important_id = 'aw6p0mya6v3r96vyj8kooxa5v'
message.labels.delete(important_id)
message.save!
method PUT
endpoint https://api.nylas.com/messages/:id
authentication Access Token as HTTP Basic Auth username
request body JSON-encoded attribute-value pairs

Specify the following attributes as a JSON-encoded object in the request body.

Attribute Description
label_ids array Array of label IDs to apply, overwriting all previous labels.

Note that the array of label IDs specified will overwrite all previous labels. When making label modifications, we strongly suggest that your application fetch the latest message object before applying changes in order to not accidentally remove labels the user has applied.

Modifying labels and folders can be performed at the thread level as well, which causes the actions to be applied to all of its messages. See the Threads documentation for more details.

Expanded Message View

The expanded message view exposes several additional RFC2822 headers, useful for implementing custom threading or cross-mailbox identification.

method GET
endpoints https://api.nylas.com/messages?view=expanded
https://api.nylas.com/messages/:id?view=expanded
authentication Access Token as HTTP Basic Auth username

The following block is added to the message object (documented above).

{
  "headers": {
     "In-Reply-To": "<evh5uy0shhpm5d0le89goor17-0@mailer.nylas.com>",
     "Message-Id": "<84umizq7c4jtrew491brpa6iu-0@mailer.nylas.com>",
     "References": ["<evh5uy0shhpm5d0le89goor17-0@mailer.nylas.com>"]
  }
}
Header Description
Message-Id optional Generated by clients while sending messages. It is different from a message’s ID returned by the Nylas API (the message object’s id). Unlike the id, the Message-Id header is not guaranteed to be unique since it is generated by clients. This field may be null.
In-Reply-To optional The parent Message-Id to which this message replied. Expected null for messages that are not replies.
References optional A list of Message-Ids related to a given message. Expected empty for messages which are not replies or related to existing messages.

Note that these values are unrelated to Nylas object IDs. Because they are provided by clients without validation, there is no guarantee of their accuracy, uniqueness, or consistency.

Raw message contents

Example Request

curl https://api.nylas.com/messages/y7o8tgaisyldf7otagu \
    -H "Accept: message/rfc822"

Example Response

Delivered-To: ben.bitdiddle1861@gmail.com
Received: by 10.36.105.83 with SMTP id e80csp448398itc;
        Mon, 2 Mar 2015 22:32:19 -0800 (PST)
X-Received: by 10.140.146.6 with SMTP id 6mr57679712qhs.44.1425364337630;
        Mon, 02 Mar 2015 22:32:17 -0800 (PST)
Return-Path: <golang-nuts+bncBC35DTG33YGBB3NK2WTQKGQEPOXSM4Q@googlegroups.com>
Received: from mail-qg0-x23b.google.com (mail-qg0-x23b.google.com. [2607:f8b0:400d:c04::23b])

<<<Raw mime body starts here...>>

Example Request

raw_contents = msg.raw

If you need to access some specific email headers or data that is not exposed by the standard message API, you can request the original raw message data originally downloaded from the mail server. Setting the Accept header to message/rfc822 will return the entire raw message object in RFC 2822 format, including all MIME body subtypes and attachments.

method GET
endpoints https://api.nylas.com/messages/:id
headers Accept: message/rfc822
authentication Access Token as HTTP Basic Auth username

Folders

Folders behave like normal IMAP or filesystem folders. A message can only exist within one folder at a time, but a thread with many messages may span several folders.

Folders are only supported on accounts for which organization_unit is folder.

Listing Folders

curl https://api.nylas.com/folders

Response

[
    {
        "id": "4zv7pgvihjvuptbwv57kiz62",
        "object": "folder",
        "name": "inbox",
        "display_name": "INBOX",
        "account_id": "awa6ltos76vz5hvphkp8k17nt"
    },
    {
        "id": "76zrfd8ln5zo2swalu1yojhty",
        "name": "archive",
        "display_name": "2015 Archive",
        "account_id": "awa6ltos76vz5hvphkp8k17nt",
        "object": "folder"
    }
]

Listing Folders

nylas.folders.each do |folder|
    puts folder.display_name
end

Response

INBOX
2015 Archive
method GET
endpoints https://api.nylas.com/folders
https://api.nylas.com/folders/:id
authentication Access Token as HTTP Basic Auth username
Attribute Description
id string Globally unique object identifier
object string A string describing the type of object (value is “folder”)
account_idstring Reference to parent account object
name string Standard categories type, based on RFC-6154.
Can be one of the following:
  • inbox
  • all
  • trash
  • archive
  • drafts
  • sent
  • spam
  • important
  • null (regular user-created folder)
display_name string Localized name of folder, matching what is presented in their other mail apps. If you are displaying folders, use this instead of name.

Creating a folder

Create a folder

curl https://api.nylas.com/folders \
    -d '{"display_name": "My New Folder"}'

Response

{
    "id": "d121cvdyjhgacaqyymzjg5prl",
    "name": null,
    "display_name": "My New Folder",
    "account_id": "awa6ltos76vz5hvphkp8k17nt",
    "object": "folder"
}

Create a folder

folder = account.folders.create()
folder.display_name = 'My Folder'
folder.save()

Create a folder

fld = nylas.folders.build(:display_name => 'My Folder',
                          :name => 'folder')
fld.save!

You can easily create new folders on accounts where the organization_unit is set to folder. Generally this is all non-Gmail/Google Apps accounts.

method POST
endpoint https://api.nylas.com/folders
authentication Access Token as HTTP Basic Auth username
request body JSON-encoded attribute-value pair

Specify the following attributes as a JSON-encoded object in the request body.

Attribute Description
display_name string Human-readable name for the new folder

This endpoint will return a new folder object upon success. An error will be returned if the supplied display_name is too long, or a conflicting folder already exists.

Nested folders

IMAP has very limited support for nested folders: it encodes a folder’s path in its name. For example, the folder Accounting/Taxes will actually be named Accounting.Taxes or even INBOX.Accounting.Taxes depending on your IMAP server. To complicate things, different IMAP servers use different path separators (for example, Taxes.Accounting` on server A will beTaxes\Accounting` on server B).

The Nylas API handles nested IMAP folders transparently. Creating a Taxes/Invoices folder using the API will create a folder with the right path separators (i.e: depending on your server, INBOX.Taxes.Invoices or Taxes/Invoices).

Renaming a folder

Renaming a folder

curl -X PUT https://api.nylas.com/folders/:folder_id \
    -d '{"display_name": "Old Homework"}'

Response

{
    "id": "d121cvdyjhgacaqyymzjg5prl",
    "name": null,
    "display_name": "New Folder Name",
    "account_id": "awa6ltos76vz5hvphkp8k17nt",
    "object": "folder"
}

Renaming a folder

folder = account.folders.first()
folder.display_name = 'New Folder Name'
folder.save()

Renaming a folder

folder = account.folders.first()
folder.display_name = 'New Folder Name'
folder.save!

The display_name attribute of a folder can modified, and these changes will propagate back to the account provider. Note that the core folders such as INBOX, Trash, etc. often cannot be renamed.

method PUT
endpoints https://api.nylas.com/folders/:id
authentication Access Token as HTTP Basic Auth username
request body JSON-encoded attributes to overwrite

Specify the following attributes as a JSON-encoded object in the request body.

Attribute Description
display_name string Rename the folder to this value. Should be human-readable, as this will appear in the user’s other mail apps.

A successful request will return the full updated folder object.

Deleting a folder

Delete a folder

curl -X DELETE https://api.nylas.com/folders/d121cvdyjhgacaqyymzjg5prl

Folders can be deleted by issuing a DELETE request to the folder’s URI. Folders must be emptied before being deleted to prevent the accidental deletion of threads. If the requested folder is not empty, the server will respond with a Forbidden error.

method DELETE
endpoints https://api.nylas.com/folders/:id
authentication Access Token as HTTP Basic Auth username

Filtering

Filter by category

All threads in trash

curl https://api.nylas.com/threads?in=trash

Note: a user may have more than one folder for trash.

Filter by folder name

All threads in a folder with the display name “Papierkorb”

curl https://api.nylas.com/threads?in=Papierkorb

Filter by category

All threads in trash

threads = nylas.threads.where(:in => 'trash')

Note: a user may have more than one folder for trash.

Filter by folder name

All threads in a folder with the display name “Papierkorb”

threads = nylas.threads.where(:in => 'Papierkorb')

The endpoints for messages, threads, and files support Filters for folders using the in URL parameter. Simply pass a folder id, name, or display_name value. This conveniently has the same format for both labels and folders, so you application can specify a single filtering request independent of organization unit. See the Filters documentation for more details.

Labels

Labels are equivalent to Gmail labels. Messages can have more than one label, which is popular for users who set up mail filters.

Labels are only supported on accounts for which organization_unit is label.

Listing Labels

curl https://api.nylas.com/labels

Response

[
    {
        "id": "4zv7pgvihjvuptbwv57kiz62",
        "name": "inbox",
        "display_name": "Posteingang",
        "account_id": "awa6ltos76vz5hvphkp8k17nt",
        "object": "label"
    },
    {
        "id": "76zrfd8ln5zo2swalu1yojhty",
        "name": "sent",
        "display_name": "Gesendet",
        "account_id": "awa6ltos76vz5hvphkp8k17nt",
        "object": "label"
    },
    {
        "display_name": "Archivieren",
        "id": "c7ld8stcsxb9mi62obv3wgsi7",
        "name": "archive",
        "account_id": "awa6ltos76vz5hvphkp8k17nt",
        "object": "label"
    },
    {
        "display_name": "homework",
        "id": "56po63srws43nht7owyt5knz4",
        "name": null,
        "account_id": "awa6ltos76vz5hvphkp8k17nt",
        "object": "label"
    }
]

Listing Labels

for label in account.labels:
    print label
method GET
endpoints https://api.nylas.com/labels
https://api.nylas.com/labels/:id
authentication Access Token as HTTP Basic Auth username
Attribute Description
id string Globally unique object identifier
object string A string describing the type of object (value is “label”)
account_idstring Reference to parent account object
name string Standard categories type, based on RFC-6154.
Can be one of the following:
  • inbox
  • all
  • trash
  • archive
  • drafts
  • sent
  • spam
  • important
  • null (regular user-created label)
display_name string Localized name of label, matching what is presented in their other mail apps. If you are displaying labels, use this instead of name.

Creating a label

Create a label

curl -X POST https://api.nylas.com/labels \
    -d '{"display_name": "My New Label"}'

Response

{
    "id": "d121cvdyjhgacaqyymzjg5prl",
    "name": null,
    "display_name": "My New Label",
    "account_id": "awa6ltos76vz5hvphkp8k17nt",
    "object": "label"
}

Create a label

label = account.labels.create()
label.display_name = 'My Label'
label.save()

You can easily create new labels on accounts where the organization_unit is set to label. Generally this is only Gmail/Google Apps accounts.

method POST
endpoint https://api.nylas.com/labels
authentication Access Token as HTTP Basic Auth username
request body JSON-encoded attribute-value pair

Specify the following attributes as a JSON-encoded object in the request body.

Attribute Description
display_name string Human-readable name for the new label

This endpoint will return a new label object upon success. An error will be returned if the supplied display_name is too long, or a conflicting label already exists.

Renaming a label

Renaming a label

curl -X PUT https://api.nylas.com/labels/:label_id \
    -d '{"display_name": "New Label Name"}'

Response

{
    "id": "d121cvdyjhgacaqyymzjg5prl",
    "name": null,
    "display_name": "New Label Name",
    "account_id": "awa6ltos76vz5hvphkp8k17nt",
    "object": "label"
}

Renaming a label

folder = account.labels.first()
folder.display_name = 'New Label Name'
folder.save()

The display_name attribute of a label can modified, and these changes will propagate back to the account provider. Note that the core labels such as Inbox, Trash, etc. cannot be renamed.

method PUT
endpoints https://api.nylas.com/labels/:id
authentication Access Token as HTTP Basic Auth username
request body JSON-encoded attributes to overwrite

Specify the following attributes as a JSON-encoded object in the request body.

Attribute Description
display_name string Rename the label to this value. Should be human-readable, as this will appear in the user’s other mail apps.

A successful request will return the full updated label object.

Deleting a label

Delete a label

curl -X DELETE https://api.nylas.com/labels/d121cvdyjhgacaqyymzjg5prl

Labels can be deleted by issuing a DELETE request to the label’s URI. A label can be deleted even if it still has associated messages.

method DELETE
endpoints https://api.nylas.com/labels/:id
authentication Access Token as HTTP Basic Auth username

Filtering

Filter by category

All threads in the inbox

curl https://api.nylas.com/threads?in=inbox

Filter by label name

All threads with the label “Homework”

curl https://api.nylas.com/threads?in=Homework

The endpoints for messages, threads, and files support Filters for labels using the in URL parameter. Simply pass a label id, name, or display_name value. This conveniently has the same format for both labels and labels, so you application can specify a single filtering request independent of organization unit. See the Filters documentation for more details.

Drafts

A draft is a special kind of message which has not been sent, and therefore its body contents and recipients are still mutable. The drafts endpoints let you read and modify existing drafts, create new drafts, send drafts, and delete drafts. Draft modifications are propagated to the mailbox provider in all cases, excluding Microsoft Exchange systems.

The draft object

Draft objects are similar to message objects sent via the API, except that they have an additional version parameter. Each time the draft is updated, its version is incremented. (The draft’s ID stays the same.)

method GET
endpoints https://api.nylas.com/drafts/
https://api.nylas.com/drafts/:id
authentication Access Token as HTTP Basic Auth username

Responses are encoded as UTF-8 JSON objects with the following attributes:

Attribute Description
idstring Globally unique object identifier
objectstring A string describing the type of object (value is “draft”)
account_idstring Reference to parent account object
thread_idstring Reference to parent thread object. If this is a new draft, the thread will be empty.
subjectstring Subject line of the draft
reply_to_message_id string ID of a message this draft is a reply to, allowing the sending API to include threading-specific headers for other mail clients
from array Array containing a single name+email pair to set as the “from” header. (See “Aliases” below.)
reply_to array Array of name+email pairs to set an alternative Reply-To header in the final sent message
to array Array of name+email pairs of recipients
cc array Array of name+email pairs of recipients to be cc’d
bcc array Array of name+email pairs of recipients to be bcc’d
dateunix timestamp Timestamp of the last modification of the draft
unread boolean Believe it or not, drafts also have an unread state
starred boolean Starred or flagged state (mutable)
snippet string A shortened plain-text preview of the draft body
body string The full HTML draft body text
files array Array of file objects, if draft includes attachments
events array Array event objects, if draft includes calendar invites
folderfolder object A single folder object indicating the location of the draft, present only if the parent account’s organization_unit is folder. Customarily this is a folder where name is drafts, but not always.
labelsarray An list of label objects, present only if the parent account’s organization_unit is "label". These have Gmail-style semantics and can be arbitrarily added and removed from messages.
versioninteger Incrementing value related to draft updates.
You can use this to compare revisions, or invalidate your local cache.

Creating Drafts

Creating a draft with curl & heredoc

curl https://api.nylas.com/drafts -d @- <<REQUEST_BODY
{
    "subject": "Dinner on Friday?",
    "to": [
        {
            "name": "Ben Bitdiddle",
            "email": "ben.bitdiddle@gmail.com"
        }
    ],
    "cc": [],
    "bcc": [],
    "body": "<html><body>....</body></html>",
    "file_ids": [
        "bgmzg0qp61oqrrmpadboiiyg3",
        "aikfl1kl73r69hevrm018jqzw"
    ],
    "version": 2
}
REQUEST_BODY

Creating a draft with the Nylas Ruby SDK

# Create a new draft
draft = nylas.drafts.build(
  :to => [{:name => 'Ben Gotow', :email => 'ben@nylas.com'}],
  :subject => "Sent by Ruby",
  :body => "Hi there!<strong>This is HTML</strong>"
)

# Modify attributes as necessary
draft.cc = [{:name => 'Michael', :email => 'mg@nylas.com'}]

# Add a file we uploaded as an attachment
draft.attach(file)

# Save the draft
draft.save!

Creating a draft with the Nylas Node SDK

// Create a new draft
var draft = nylas.drafts.build({
    subject: 'Sent by NodeJS',
    to: [{email: 'ben@nylas.com'}],
    body:  "Hi there!<strong>This is HTML</strong>",
});

// Modify attributes as necessary
draft.cc = [{name: 'Michael', email: 'mg@nylas.com'}]

// Save the draft
draft.save().then(function(draft) {
    console.log(draft.id + ' was saved');
});
method POST
endpoint https://api.nylas.com/drafts
authentication Access Token as HTTP Basic Auth username
request body JSON-encoded attribute-value pairs. All are optional.

Specify the following attributes as a JSON-encoded object in the request body. All are optional, although note that at least one recipient in to, cc, or bcc must be specified before sending.

Attribute Description
subjectstring Subject line of the draft
to array Array of name+email pairs of recipients
cc array Array of name+email pairs of recipients to be cc’d
bcc array Array of name+email pairs of recipients to be bcc’d
from array Array containing a single name+email pair to set as the “from” header. (See “Aliases” below.) Note that not all providers support setting this in a draft.
reply_to array Array of name+email pairs to set an alternative Reply-To header in the final sent message. Note that not all providers support setting this in a draft.
body string The full HTML draft body text
file_ids array Array of file IDs, if draft includes attachments. Note that creating a draft will fail if these files have not yet been uploaded.

Note again that all of these parameters are optional. If omitted, an empty draft will still be created. A successful response will contain the newly created draft object.

Attachments

Creating a draft will fail if the files with the referenced file_ids have not been uploaded. See files for more details on how to upload and reference attachments.

Replies

If the draft is a response to an existing message, you should provide the message’s ID as a reply_to_message_id attribute and omit the subject parameter. Note that you still must explicitly specify the message’s recipients in the to, cc or bcc fields of the post body. (This is by design to prevent any ambiguity about whom the message will be sent to.)

Aliases

If you would like to use an alias for sending and/or receiving emails, you can optionally set the from or reply_to fields. Note that if the given address is actually not an alias, most SMTP servers will either reject the message or silently replace it with the primary sending address.

If the from and reply_to fields are omitted, the account’s default sending name and address will be used.

Updating a draft

method PUT
endpoints https://api.nylas.com/drafts/:id
authentication Access Token as HTTP Basic Auth username

Updating a draft is as simple as issuing a PUT request to the draft’s URI.

Put body parameters:

The request body must contain the version of the draft you wish to update. Other fields are optional and will overwrite previous values.

Updating a draft returns a draft object with the same ID but different version. When submitting subsequent send or save actions, you must use this new version.

Deleting a draft

Delete a draft

curl -X DELETE https://api.nylas.com/drafts/bshtyl5xwcebolj4rkpwzi46h \
    -d '{"version": 3}'

Delete a draft

draft.destroy

Delete a draft

draft.delete(function(err) {
    if (err == null)
        console.log('Deleted');
});

Drafts can be deleting by issuing a DELETE request to the draft’s URI. The request body must contain a JSON object specifying the latest version, or deletion will fail. This is to prevent accidental deletion of drafts which have been updated.

method DELETE
endpoints https://api.nylas.com/drafts/:id
authentication Access Token as HTTP Basic Auth username
request body JSON-encoded attribute-value pairs. Required:
  • version

Sending

The Nylas platform provides two ways to send messages: either through sending an existing draft, or by sending directly. Both systems send mail through the account’s original SMTP/ActiveSync gateway, just as if they were sent using any other app. This means messages sent through Nylas have very high deliverability (i.e. not landing in Gmail’s promotions tab), but may also be subject to backend provider rate-limiting and abuse detection. Make sure to send wisely!

method POST
endpoints https://api.nylas.com/send
authentication Access Token as HTTP Basic Auth username
request body JSON-encoded attribute-value pairs, specified below

All sending operations are synchronous, meaning the request will block until the draft has succeeded or failed. In the event of failure, the sending API will not automatically retry.

We recommend that you apply backoff when HTTP 503s are returned. Your app may need to wait 10-20 minutes, or SMTP servers may continue to refuse connections for a particular account. For some providers like Gmail, there are hard limits on the number of messages you can send per day.

If large-volume sending continues to fail for your application, we recommend switching to a transactional sending service like Mailgun, Sendgrid, Mandrill, or Amazon SES.

Sending drafts

Sending an existing draft

curl -X POST https://ACCESS_TOKEN@api.nylas.com/send -d '
{
    "draft_id": "9nhhb7w3tinsn4zkg9vjr3cxz",
    "version": 2
}
'

Successful response will include a full new message object.

Sending an existing draft

message = draft.send!

Successful response will include a full new message object.

Existing drafts can be sent by providing their ID and version. Existing drafts can be sent by providing their ID and version.

Attribute Description
draft_idstring ID of existing draft
version integer Version of the draft. Must be most recent or the request will fail.

A successful response will include a full new message object.

Sending directly

Example Request

curl -X POST https://ACCESS_TOKEN@api.nylas.com/send -d '
{
    "reply_to_message_id": "84umizq7c4jtrew491brpa6iu",
    "body" : "Sounds great! See you then.",
    "to": [
        {
            "name": "Bill",
            "email": "wbrogers@mit.edu"
        }
    ]
}
'

Successful response includes a new message object.

Example Request

message = nylas.drafts.build(
  :to => [{:name => 'Ben Gotow', :email => 'ben@nylas.com'}],
  :subject => "Sent by Ruby",
  :body => "Hi there!<strong>This is HTML</strong>").send!

Messages can be sent directly, without saving them as drafts beforehand.

Attribute Description
subject string Subject line of the draft
reply_to_message_id string ID of a message this draft is a reply to, allowing the sending API to include threading-specific headers for other mail clients
from array Array containing a single name+email pair to set as the “from” header. (See “Aliases” below.)
reply_to array Array of name+email pairs to set an alternative Reply-To header in the final sent message
to array Array of name+email pairs of recipients
cc array Array of name+email pairs of recipients to be cc’d
bcc array Array of name+email pairs of recipients to be bcc’d
body string The full HTML body to send. If replying to a message, you should include quoted text here.
file_ids array Array of file IDs, if you are including attachments. Note that sending will fail if these files have not yet been uploaded.
tracking object Optional object that allows you to enable message tracking features for this message or thread.

Note that all of these attributes are individually optional. However, sending a message will fail if there is no recipient specified in either to, cc, or `bcc.

A successful response will include a full new message object.

Sending raw MIME

Example Request

curl -X POST https://ACCESS_TOKEN@api.nylas.com/send -H "Content-Type: message/rfc822" -d 'MIME-Version: 1.0
  Content-Type: text/plain; charset=UTF-8
  In-Reply-To: <84umizq7c4jtrew491brpa6iu-0@mailer.nylas.com>
  References: <84umizq7c4jtrew491brpa6iu-0@mailer.nylas.com>
  Subject: Meeting on Thursday
  From: Bill <wbrogers@mit.edu>
  To: Ben Bitdiddle <ben.bitdiddle@gmail.com>

  Hey Ben,

  Would you like to grab coffee @ 2pm this Thursday?"
  Bill
  '
method POST
endpoints https://api.nylas.com/send
headers Content-Type: message/rfc822
authentication Access Token as HTTP Basic Auth username
request body RFC-2822-compatible message object, with at least one To, Cc, or Bcc recipient header set

You can also send via submitting raw MIME message object. The submitted object is entirely preserved, except the Bcc header which is removed. Additional headers used by Nylas may be added.

If the message is in reply to an existing message, you should make sure to include the In-Reply-To and References headers. These headers are set to the Message-Id header of the message you are replying to and Message-Id header of related messages, respectively. For more details, see this excellent article by djb.

Sending inline images

Sending inline images example

<div>
    <p>Before image</p>
    <img src="cid:472ypl5vqbnh0l2ac3y71cdks">
    <p>After image</p>
</div>

You can send image attachments inline in the body of your emails. Simply reference one of the attached file_ids in an img tag. For example, if one of your attachments has file_id = '472ypl5vqbnh0l2ac3y71cdks' then you could display it inline like in the example to the right. Dont’ forget to prepend the file_id with cid: for the src attribute.

Sending Errors

Example malformed sending response (note the missing period in email address)

curl -X POST https://ACCESS_TOKEN@api.nylas.com/send -d '
{
    "subject": "Lunch today?",
    "body" : "Lets go somewhere good!",
    "to": [
        {
            "name": "Ben Bitdiddle",
            "email": "benbitdiddle@gmailcom"
        }
    ]
}
'

Response

HTTP/1.1 400 BAD REQUEST
Server: nginx/1.6.2
Date: Mon, 17 Aug 2015 00:04:59 GMT
Content-Type: application/json
Content-Length: 89
Access-Control-Allow-Headers: Authorization,Accept,Cache-Control,X-Requested-With,Content-Type
Access-Control-Allow-Methods: GET,PUT,POST,DELETE,OPTIONS
Access-Control-Allow-Credentials: true
Strict-Transport-Security: max-age=31536000;

{
  "message": "Invalid recipient address benbitdiddle@gmailcom",
  "type": "invalid_request_error"
}

Sometimes message delivery can fail if the user’s email gateway rejects the message. This could happen for a number of reasons, including illegal attachment data, bad credentials, or rate limiting. If your message is sent successfully, the server will respond with an HTTP response code of 200 OK. If your message couldn’t be sent, the server will respond with an appropriate error code.

Status Code Reason
200OK Your message was sent.
400 Bad Request Your request was malformed, or contained an invalid parameter. The most common issue is invalid JSON.
402 Message Rejected The mail provider rejected your message because of its content or recipients. Note this means that your message may have been delivered to only a subset of participants if the message includes “Sending to at least one recipient failed”.
403 Unauthorized The server was unable to authenticate with the user’s mail provider. Re-authenticate the user and try again.
422 Mail provider error An error occurred while the mail provider was sending the message. See the server_error in the response body JSON for more information.
429 Quota Exceeded The user has exceeded their mail provider’s sending quota. Unfortunately there is no reliable way to determine these limits. Wait and try again later.
503 Service Unavailable There was an error connecting to the user’s mail provider. Wait and try again.

In addition, the response body contains a JSON object with information about the specific error, including the following attributes:

Status Code Reason
type string Error type
message string A brief human-readable description of the error.
server_error string (optional) The original error returned by the user’s mail server.

See Errors for more information about error responses and how to handle them.

Files



The files endpoint manages data attached to messages. It allows you to download existing attachments from messages and threads, as well as upload new files to be sent. Note that before creating or modifying a draft to include an attachment, you must upload it via this API and use the returned file ID.

Metadata

Listing all files

curl  https://api.nylas.com/files

Response:

[{
    "content_type": "image/jpeg",
    "filename": "unnamed.jpg",
    "id": "dyla86usnzouam5wt7wt2bsvu",
    "message_ids": [
        "cud32592sewzy834bzhsbu0kt"
    ],
    "content_id": "huy78t6faujljaklasf@example.com",
    "account_id": "6aakaxzi4j5gn6f7kbb9e0fxs",
    "object": "file",
    "size": 8380
}, {
    "content_type": "application/msword",
    "filename": "Reinstatement of Corporation.doc",
    "id": "9tm2n206vdj29wrhcxfvmvo4o",
    "message_ids": [
        "93mtrpk4uo3wsvwcpb5yh57kp"
    ],
    "account_id": "6aakaxzi4j5gn6f7kbb9e0fxs",
    "object": "file",
    "size": 100864
}, {
    "content_type": null,
    "filename": null,
    "id": "cp46ncjoehegh200d3h7asvcr",
    "account_id": "6aakaxzi4j5gn6f7kbb9e0fxs",
    "object": "file",
    "size": 7574
}

]

Listing all files

nylas.files.each do |file|
    puts file.name
end

Output:

unnamed.jpg
Reinstatement of Corportion.doc
nil

Listing all files

nylas.files.list({}, function(err, files) {
    for (var i = 0; i < files.length; i++) {
        console.log(files[i].name);
    }
});

Response:

unnamed.jpg
Reinstatement of Corportion.doc
null

Actual attached files may be relatively large (upwards of 25MB), so this API has separate endpoints for requesting file metadata and downloading the actual file.

method GET
endpoints https://api.nylas.com/files
https://api.nylas.com/files/:id
authentication Access Token as HTTP Basic Auth username

Responses are encoded as UTF-8 JSON objects with the following attributes:

Attribute Description
idstring Globally unique object identifier
objectstring A string describing the type of object (value is “file”)
account_idstring Reference to parent account object
filename string Name of the file, if available
size integer Size of the file, in bytes
content_type string Content-Type of the file, sometimes also called Internet media type or MIME type.
message_ids array Array of identifiers for messages that contain this attachment. (Not guaranteed to be a complete set)
content_id string Included if file was attached as a inline media. Using this value, your app can locate the associated cid URL in the message body and embed the resource.

Downloading

Example file metadata request:

curl  https://api.nylas.com/files/dyla86usnzouam5wt7wt2bsvu/

Response:

{
    "content_type": "image/jpeg",
    "filename": "sailing_photo.jpg",
    "id": "dyla86usnzouam5wt7wt2bsvu",
    "message_ids": ["cud32592sewzy834bzhsbu0kt"],
    "account_id": "6aakaxzi4j5gn6f7kbb9e0fxs",
    "object": "file",
    "size": 8380
}

Download the actual file data

curl --include https://api.nylas.com/files/dyla86usnzouam5wt7wt2bsvu/download

Response

HTTP/1.1 200 OK
Server: nginx/1.6.2
Date: Mon, 17 Aug 2015 01:18:54 GMT
Content-Type: application/octet-stream
Content-Length: 8380
Content-Disposition: attachment; filename=sailing_photo.jpg
Access-Control-Allow-Headers: Authorization,Accept,Cache-Control,X-Requested-With,Content-Type
Access-Control-Allow-Methods: GET,PUT,POST,DELETE,OPTIONS
Access-Control-Allow-Credentials: true
Strict-Transport-Security: max-age=31536000;

< binary file data follows >

Note the filename included in Content-Disposition.

Example file metadata request:

file = nylas.files.find('dyla86usnzouam5wt7wt2bsvu')
puts file.size

Response:

8380

Example file metadata request:

nylas.files.find('dyla86usnzouam5wt7wt2bsvu').then(function(err, file) {
    console.log(file.size);
});

Response:

8380

Files can be downloaded by appending /download to the file metadata URI. If available, the response will include the filename in the Content-Disposition header.

method GET
endpoints https://api.nylas.com/files/:id/download
authentication Access Token as HTTP Basic Auth username

Uploading

Upload a file located at /path/to/file.jpg

curl https://api.nylas.com/files -F "file=@/path/to/file.jpg"

Response

[
    {
        "content_type": "image/jpeg",
        "filename": "2015-08-08 15.15.29.jpg",
        "id": "3qfe4k3siosfjtjpfdnon8zbn",
        "account_id": "6aakaxzi4j5gn6f7kbb9e0fxs",
        "object": "file",
        "size": 762878
    }
]

Upload a file located at /path/to/file.jpg

file = nylas.files.build(:file => File.new("/path/to/file.jpg", 'rb'))
file.save!
method POST
endpoints https://api.nylas.com/files
authentication Access Token as HTTP Basic Auth username

This endpoint is used to transfer files to Nylas, which must be done before adding them to a draft message. Data should be sent as multipart-form data with a single field named file.

A successful upload will return an array with a single file object. This object’s ID may be attached to a draft by appending it to file_ids array of the draft object. Additionally, if the object is an image it may be included inline in the body of the email by referencing it inside an img tag like so: <img src="cid:file_id">.

Using Filters

Return metadata for all zip files

curl https://api.nylas.com/files?content_type=application%2Fzip

Return metadata for all Microsoft Word files

curl https://api.nylas.com/files?content_type=application%2Fmsword

Note the “/” character in the content-type has been replaced by the percent-encoded value %2F.

Return metadata for all zip files

zip_files = nylas.files.where(:content_type => 'application/zip')

Return metadata for all Microsoft Word files

word_files = nylas.files.where(:content_type => 'application/msword')

Return metadata for all zip files

nylas.files.list({content_type: 'application/zip'}).then(callback)

Return metadata for all Microsoft Word files

nylas.files.list({content_type: 'application/msword'}).then(callback)

This endpoint supports filters and pagination, which allow you to fetch multiple files matching specific criteria and iterate through a large set of files.

URL Parameter Description
filename string Return files that have the given filename
message_id string Return files received in a specific message
content_type string Return all files of a single Content-Type (e.g. image/jpeg)

Some example Content-Type values corresponding to popular file extensions.

Document Content-Type
PNG images image/png
JPEG images image/jpeg
PDF documents application/pdf
ZIP archives application/zip
MS Word (.doc) application/msword
MS Excel (.xls) application/vnd.ms-excel
MS Powerpoint (.ppt) application/vnd.ms-powerpoint
MS Word (.docx) application/vnd.openxmlformats-officedocument.wordprocessingml.document
Microsoft Powerpoint (.pptx) application/vnd.openxmlformats-officedocument.presentationml.pesentation
Microsoft Excel (.xlsx) application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

Here is a more complete list of Content Types.

Calendars

Example Request

curl https://api.nylas.com/calendars

Example Response

[
    {
        "description": null,
        "id": "67qmz3fuk9wfljwj1w8ngshkc",
        "name": "Calendar",
        "account_id": "bh1vu31mw9ap7ri5k166ah9uo",
        "object": "calendar",
        "read_only": false
    },
    {
        "description": "Emailed events",
        "id": "b4xm1jjibrxkymq81dbgeul8",
        "name": "Emailed events",
        "account_id": "bh1vu31mw9ap7ri5k166ah9uo",
        "object": "calendar",
        "read_only": true
    }
]

From this response we can see that the account has two calendars, and one that can be modified.

Example Request

calendars = nylas.calendars
calendars.each do |cal|
    puts cal.name
end

Example Output

Calendar
Conference room
Nylas OOO

Example Request

for cal in client.calendars:
    print cal.name
end

Example Output

Calendar
Conference room
Nylas OOO

Example Request

nylas.calendars.list(function(err, calendars) {
    for(var i = 0; i < calendars.length; i++))
        console.log(calendars[i].name);
});

Example Output

Calendar
Conference room
Nylas OOO

Each account connected to Nylas can have zero or more calendars, and each calendar has a collection of individual events. The calendar object is very simple, and mostly serves as a container for events. The read_only flag on a calendar indicates whether or not you can modify its properties or make changes to its events.

method GET
endpoints https://api.nylas.com/calendars
https://api.nylas.com/calendars/:id
authentication Access Token as HTTP Basic Auth username

The calendar endpoint supports pagination (although most users have only a few calendars).

Provider-backed calendars

The primary calendar of the account is usually named the same as the email address, or sometimes simply called “Calendar.” Users may also have other custom calendars, or access to shared team calendars. See events for more details.

Events can be viewed, added, modified, and deleted on calendars where read_only is false. Changes are automatically synced back to the provider.

The “Emailed events” calendar

All accounts also include a special calendar called “Emailed events” which contains event invitations that have been sent to the user’s mailbox. This calendar is read-only, meaning events cannot be added, updated, or deleted. However, the events can be RSVP’d to. See the events documentation for details.

Events



Events are objects within a calendar, generally supporting all features of modern scheduling apps. Using the calendar APIs, your application can schedule events, send meeting invitations, RSVP, and more.

The event object

Example Request

curl https://api.nylas.com/events/4ee4xbnx7pxdb9g7c2f8ncyto

Example Response

{
    "object": "event",
    "id": "4ee4xbnx7pxdb9g7c2f8ncyto",
    "calendar_id": "ci0k1wfyv533ccgox4t7uri4h",
    "account_id": "14e5bn96uizyuhidhcw5rfrb0",
    "description": null,
    "location": null,
    "owner": "Ben Bitdiddle <example@gmail.com>",
    "participants": [
        {
            "email": "example@gmail.com",
            "name": "Ben Bitdiddle",
            "status": "yes"
        }
    ],
    "read_only": false,
    "title": "Meeting with Ben Bitdiddle",
    "when": {
        "object": "timespan",
        "end_time": 1408123800,
        "start_time": 1408120200
    },
    "busy": true,
    "status": "confirmed"
}

Example Request

event = nylas.event.find('ac123acd123ef123')
puts event.title

Example Output

Monday morning meeting

Example Request

nylas.events.find('ac123acd123ef123').then(event) {
    console.log(event.title);
});

Example Output

Monday morning meeting
method GET
endpoints https://api.nylas.com/events
https://api.nylas.com/events/:id
authentication Access Token as HTTP Basic Auth username

Optional URL Parameters:

attribute description
expand_recurring boolean If set to true, expands single recurring events into individual event instances that fall within the requested time range.
show_cancelled boolean If set to true, also return cancelled events. (false by default)

Responses are encoded as UTF-8 JSON objects with the following attributes:

attribute description
id string Globally unique object identifier
object string A string describing the type of object (value is “event”)
account_id string Reference to parent account object
calendar_id string Reference to the parent calendar object
title string Title of the event, usually kept short.
description string Description of the event, which may contain more details or an agenda.
when subobject One of four subobjects corresponding to the time and duration of an event: time, timespan, date, or datespan. See below for more details.
location string Location, such as a physical address or meeting room name
owner string The owner of the event, usually their email or name and email.
participants array Array of others invited to the event. Keys are email, name, status. Participants may also be rooms or resources. See below for more details.
status string Either confirmed, tentative, or cancelled.
read_only boolean Whether the event can be modified
busy boolean On shared or public calendars, whether to show this event’s time block as available or not. (Also called “transparency” in some systems.)
recurrence subobject Included if the event is a master recurring event. See below for the subobject definition
master_event_id string Only included in exceptions (overrides) to recurring events, the id of the recurring event.
original_start_time unix timestamp Only included in exceptions (overrides) to recurring events, the start time of the recurring event.

Note that events are always sorted by their start date.

Subobjects

Participants

The participants attribute is returned as an array of dictionaries corresponding to participants. These include the keys:

attribute description
name string The participant’s full name (optional)
email string The participant’s email address
status string Attendance status. Allowed values are yes, maybe, no and noreply. Defaults is noreply
comment string A comment by the participant (optional)

Time

Example: the 2014 San Francisco earthquake

{
    "object": "time",
    "time": 1408875644
}

The time subobject corresponds a single moment in time, which has no duration. Reminders or alarms would be represented as time subobjects.

attribute description
object string A string describing the type of object (value is “time”)
time unix timestamp A UNIX timestamp (UTC)

Timespan

Example: a morning meeting:

{
    "object": "timespan",
    "start_time": 1409594400,
    "end_time": 1409598000
}

A span of time with a specific beginning and end time. An hour lunch meeting would be represented as timespan subobjects.

attribute description
object string A string describing the type of object (value is “timespan”)
start_time unix timestamp Starting time of the event
} end_time unix timestamp Ending time of the event

Date

A specific date for an event, without a clock-based starting or end time. Your birthday and holidays would be represented as date subobjects.

Example: the birthdate of Alan Turing:

{
    "object": "date",
    "date": "1912-06-23"
}
attribute description
object string A string describing the type of object (value is “date”)
date date Date of occurance in ISO 8601 format.

Datespan

Example: the lifespan of Ada Lovelace

{
    "object": "datespan",
    "start_date": "1815-12-10",
    "end_date": "1852-11-27"
}

A span of entire days without specific times. A business quarter or academic semester would be represented as datespan subobjects.

attribute description
object string A string describing the type of object (value is “datespan”)
start_date date Start date in ISO 8601 format.
end_date date End date in ISO 8601 format.

Recurrence

Example: an event that repeats weekly

{
    "rrule": [
        "RRULE:FREQ=WEEKLY;BYDAY=MO"
    ],
    "timezone": "America/New_York"
},

If requesting events without expand_recurring, the events endpoint will only return the ‘master’ recurring event and only if it falls within the requested time range. The recurrence attribute contains recurrence info in RRULE form; this tool is helpful in understanding the RRULE spec.

attribute description
timezone string IANA time zone database formatted string (e.g. America/New_York)
rrule array Array of recurrence rule (RRULE) strings. See RFC-2445

Filtering

The events endpoint supports filters, which allow you to fetch multiple events matching specific criteria.

attribute description
event_id string Return the event with the given id
calendar_id string Return all events belonging to the referenced calendar
title string Return events whose title matches the provided value.
description string Return events whose description matches the provided value.
location string Return events whose location matches the provided value.
starts_before unix timestamp Return events that start before this timestamp.
starts_after unix timestamp Return events that start after this timestamp.
ends_before unix timestamp Return events that end before this timestamp.
ends_after unix timestamp Return events that end after this timestamp.

The events endpoint also supports Pagination.

Recurring events

Using the expand_recurring URL parameter is an easy way to expand recurring events server-side so your application doesn’t need to deal with RRULEs. Note that when using this query parameter, you must also use filters to specify a time range.

Currently, these expanded instances of recurring events are read-only. If the recurring event has individual modifications (overrides), such as a one-off time change, we will return these as individual events regardless of whether expand_recurring is set or not.

If expand_recurring is not set, we will return any one-off cancellations in addition to the base event, for apps that are expanding the recurrence client-side. A cancellation has the field cancelled set to true.

Creating events

Creating an event

curl https://api.nylas.com/events -d @- <<REQUEST_BODY
{
    "title":"Friday meeting",
    "when" : {
        "start_time": 1407542195,
        "end_time": 1407543195
    },
    "location": "Nylas HQ",
    "calendar_id": "ci0k1wfyv533ccgox4t7uri4h",
    "participants": [
        {
            "email": "example@gmail.com",
            "name": "Ben Bitdiddle"
        }
    ]
}
REQUEST_BODY

Creating an event

# Every event belongs to a calendar, so get the id of the first calendar
calendar_id = inbox.calendars.first.id
new_event = inbox.events.build(:calendar_id => calendar_id, :title => 'Friday meeting')

# Modify attributes as necessary
new_event.location = "Nylas HQ"

# Dates are expressed by the Nylas API as UTC timestamps
new_event.when = {:start_time => 1407542195, :end_time => 1407543195}

# Persist the event --- it's automatically synced back to the Google or Exchange calendar
new_event.save!

Creating an event

// Every event belongs to a calendar, so grab the first writable calendar
nylas.calendars.list({}).then(function(calendars) {
    cal = null;
    for(var i = 0; i < calendars.length; i++) {
        if (calendars[i].readOnly != true) {
            cal = calendars[i];
            break;
        }
    }

    ev = nylas.events.build({title: 'Friday meeting', calendarId: cal.id})
    // Change attributes as necessary
    ev.location = 'Nylas HQ'
    // Dates are expressed by the Nylas API as UTC timestamps
    ev.start = 1407542195
    ev.end = 1407543195

    // Persist the event --- it's automatically synced back to the Google or Exchange calendar
    ev.save();
});

New events can easily be created. They are automatically synced back to the calendar provider, such as Google Calendar or Microsoft Exchange.

method POST
endpoints https://api.nylas.com/events
authentication Access Token as HTTP Basic Auth username

Optional URL Parameters:

attribute description
notify_participants boolean If set to true, email notifications containing the calendar event will be sent to all event participants.

Updating events

Updating an event with a new location and participant

curl https://api.nylas.com/events/4ee4xbnx7pxdb9g7c2f8ncyto \
-d @- <<REQUEST_BODY
{
    "location": "Atlas Cafe (updated)",
    "calendar_id": "ci0k1wfyv533ccgox4t7uri4h",
    "participants": [
        {
            "email": "example@gmail.com",
            "name": "Ben Bitdiddle"
        },
        {
            "email": "example2@gmail.com",
            "name": "Alyssa P. Hacker"
        },

    ]
}
REQUEST_BODY

Updating an event with a new location and participant

event.location = 'Atlas Cafe (updated)'
event.participants = [{:email => "example@gmail.com", :name => 'Ben Bitdiddle'},
                      {:email => "example2@gmail.com", :name => 'Alyssa P. Hacker'}]
event.save!

Updating an event with a new location and participant

event.location = 'Atlas Cafe (updated)'
event.participants = [{email: "example@gmail.com", name: 'Ben Bitdiddle'},
                      {email: "example2@gmail.com", name: 'Alyssa P. Hacker'}]
event.save();

Updating and deleting an event is managed in a similar fashion to other endpoints with the restriction that read_only events cannot be updated and events cannot be updated or deleted from a read_only calendar.

method PUT
endpoints https://api.nylas.com/events/:id
authentication Access Token as HTTP Basic Auth username
attribute description
notify_participants boolean If set to true, email notifications containing the calendar event will be sent to all event participants.

Deleting events

method DELETE
endpoints https://api.nylas.com/events/:id
authentication Access Token as HTTP Basic Auth username

Optional URL Parameters:

attribute description
notify_participants boolean If set to true, email notifications containing the calendar event will be sent to all event participants.

Events can also be deleted from the calendar. Pass the notify_participants URL parameter to notify those who have been invited that the event has been cancelled.

Delete an event

curl -X DELETE https://api.nylas.com/events/dw3uuf9nu1ykyxf0yau70hvsm&notify_participants=true

RSVP to an event

event.destroy(notify_participants => true)

RSVPing to invitations

RSVP to an event

curl https://api.nylas.com/send-rsvp -d @- <<REQUEST_BODY
{
    "event_id": "dw3uuf9nu1ykyxf0yau70hvsm",
    "status": "yes",
    "comment": "Excited to come!"
}
REQUEST_BODY

RSVP to an event

# RSVP to an invite (Note: this only works for the events in the 'Emailed events' calendar)
# possible statuses are 'yes', 'no' and 'maybe'.
emailed_invite.rsvp!(status='yes', comment='Excited to come')

RSVP to an event

// RSVP to an invite (Note: this only works for the events in the 'Emailed events' calendar)
// possible statuses are 'yes', 'no' and 'maybe'.
ev.rsvp('yes', 'Excited to come').then(function(ev) {
    console.log('RSVP sent!');
});

The RSVP endpoint allows you to send attendance status updates to event organizers. Note this is only possible for events that appears on the “Emailed events”, which are calendar invitations.

method POST
endpoints https://api.nylas.com/send-rsvp
authentication Access Token as HTTP Basic Auth username
request body JSON-encoded attribute-value pairs, specified below
Attribute Description
event_idstring Which event you are RSVPing to. Must be a valid event ID from the “Emailed events” calendar.
statusstring Can be one of yes, no, or maybe
account_idstring Reference to parent account object

If the RSVP is successful, the event object is returned with your RSVP participant status updated. This endpoint is idempotent: this means that only one email will be sent when you issue the same request with the same body multiple times.

RSVP Errors

Behind the scenes, RSVPs work by sending an email back to the event organizer in iMIP format. Therefore, errors when RSVPing to events follow the same status codes as sending errors.

Contacts

The Nylas API provides access to the user’s contacts, making it easy to add contact autocomplete, address book integration, and more to your application.

Note that contacts are currently read-only.

method GET
endpoints https://api.nylas.com/contacts
authentication Access Token as HTTP Basic Auth username

Responses are encoded as UTF-8 JSON objects with the following attributes:

Attribute Description
idstring Globally unique object identifier
objectstring A string describing the type of object (value is “contact”)
account_idstring Reference to parent account object
name string Full name of contact
email string Email address of contact

Request a contact

curl https://api.nylas.com/contacts/8pjz8oj4hkfwgtb46furlh77

Response:

[
    {
        "name": "Ben Bitdiddle",
        "email": "ben.bitdiddle@mit.edu",
        "id": "8pjz8oj4hkfwgtb46furlh77",
        "account_id": "aqau8ta87ndh6cwv0o3ajfoo2",
        "object": "contact"
        "phone_numbers": [
            {
                "number": "8675309",
                "type": "Mobile"
            },
            {
                "number": "+1 (555) 867-5309",
                "type": "Organization main"
            },
            {
                "number": "555-867-5309",
                "type": "Home"
            },
        ]
    }
]

For Microsoft Exchange contacts, we also provide phone numbers associated with the contact. This is an experimental feature so the format may change in a backward incompatible way in the future.

For this reason, you should not rely on using it in production apps without accounting for format changes or the possibility of the attribute not always being returned in the response.

Attribute Description
phone_numbersarray Array of zero or more phone numbers, each represented as a dict with the keys “type” and “number” (values are strings)

The values for number and type are unformatted strings so any formatting, such as phone number formatting should be done on the client side. Note that duplicates may also exist.

Using filters

The contacts endpoint currently only supports one filter parameter:

Request a contact matching ben.bitdiddle@mit.edu

curl https://api.nylas.com/contacts?filter=ben.bitdiddle@mit.edu

Response:

[
    {
        "name": "Ben Bitdiddle",
        "email": "ben.bitdiddle@mit.edu",
        "id": "8pjz8oj4hkfwgtb46furlh77",
        "account_id": "aqau8ta87ndh6cwv0o3ajfoo2",
        "object": "contact"
    }
]

Request a contact matching Ben Bitdiddle

matches = nylas.contacts.where(:filter => "ben.bitdiddle@mit.edu")
matches.each do |contact|
    puts contact.name
end

Output:

Ben Bitdiddle

Request a contact matching ben.bitdiddle@mit.edu

nylas.contacts.list({filter: "ben.bitdiddle@mit.edu"}, function(err, contacts) {
    for(var i = 0; i < contacts.length; i++) {
        console.log(contacts[i].name);
    }
});

Output:

Ben Bitdiddle
URL Parameter Description
filter string Only return contacts containing this exact value for the contact’s email address

Note that this filter only returns exact matches on the value, not substring matches.

The contacts endpoint also supports Pagination.

Deltas

The Nylas Sync Engine builds a transaction log that records every change as it sychronizes your users’ mailboxes. Your application can use these changes, exposed through the Delta endpoint, to build email applications that process new data quickly without fetching an index of the user’s mailbox or performing a large number of API calls.

To use the Delta API, your application needs to maintain a sync cursor, a record of the last change you successfully processed. Each time you perform a sync, you process the deltas provided by the API and update your stored cursor.

Obtaining a Delta Cursor

Generate a cursor:

curl -X POST https://api.nylas.com/delta/latest_cursor -

Response:

{
   "cursor": "aqb0llc2ioo0bclh7uxkim9z6"
}

Generate a cursor:

cursor = nylas.latest_cursor()
puts cursor

Output:

aqb0llc2ioo0bclh7uxkim9z6

Generate a cursor:

nylas.deltas.latestCursor(function(err, cursor) {
    console.log(cursor);
}

Output:

aqb0llc2ioo0bclh7uxkim9z6

The first time you sync using the delta API, you need to obtain a cursor. In subsequent requests, your app will pass this cursor and receive changes (i.e. deltas) from the moment you request the cursor onwards.

method POST
endpoints https://api.nylas.com/delta/latest_cursor
authentication Access Token as HTTP Basic Auth username
request body Empty
Attribute Description
cursor string A cursor used to receive changes from this moment onward.

Requesting a set of deltas

Request deltas from this cursor onward

curl https://api.nylas.com/delta?cursor=aqb0llc2ioo0bclh7uxkim9z6

Sample response:

{
    "cursor_start": "aqb0llc2ioo0bclh7uxkim9z6",
    "cursor_end": "5u9kwbgyq8wgq0iqdakqt7kjl",
    "deltas": [
        {
            "object_id": "aqb0llc2ioo0bclh7uxkim9z6",
            "event": "modify",
            "object": "thread",
            "cursor": "7ciyf89wprvvkw3p9oz86swcs",
            "attributes": {
                "draft_ids": [
                    "diu1tytx7p9wnx64hdbxsypqe"
                ],
                "first_message_timestamp": 1414778436,
                "id": "71ormxuivtg52p141tpgjk3vi",
                "last_message_timestamp": 1414778436,
                "message_ids": [],
                "account_id": "f3b0j663wmm2bluq77uc4db9m",
                "object": "thread",
                "participants": [],
                "snippet": "",
                "subject": "Hello World!",
                "folders": [
                    {
                        "name": "drafts",
                        "id": "e3b0j663wmm29luq774c4db96",
                    }
                ],
                "unread": false,
                "starred": false
            }
        },
        {
            "cursor": "9vsuralamrmitihpf2zszmpmd",
            "event": "delete",
            "id": "5oly0nmkfbgnjhw00xa4i0k5l",
            "object": "folder"
        }
    ]
}

Request deltas from this cursor onward

nylas.deltas(cursor) do |event, object|
    if event == "create" or event == "modify"
        if object.is_a?(Nylas::Event)
            puts "Got an event"
            puts event.title
        end
    last_cursor = object.cursor
end

Sample response:

Friday lunch
Monday meeting (updated!)

Request deltas from this cursor onward

// Start the stream and add event handlers.
var stream = nylas.deltas.startStream(cursor);

stream.on('delta', function(delta) {
  // Handle the new delta here.
  if (delta.object == 'event' && (delta.event == 'create' || delta.event == 'modify')) {
    console.log('Got an event');
    console.log(delta.title);
  }
}).on('error', function(err) {
  // Handle errors here, such as by restarting the stream at the last cursor.
  console.error('Delta streaming error:', err);
});

Sample response:

Friday lunch
Monday meeting (updated!)

Each time your application syncs with Nylas, you provide the cursor indicating your position in the user’s mailbox history. The API request below returns a set of JSON objects representing individual changes to the user’s mailbox: folder and label changes, new messages, etc.

method GET
endpoints https://api.nylas.com/delta
authentication Access Token as HTTP Basic Auth username

Required URL Parameters:

attribute description
cursor string A cursor value saved from a previous response.

After processing these deltas, your application should update its stored cursor to the value of cursor_end in the response. The deltas endpoint often only returns a subset of deltas available, so it’s important to continue requesting deltas until your application receives a value for cursor_end that is identical to cursor_start. This indicates that you have requested all delta events up to the current moment.

Each element of the delta attribute in the response contains the following fields:

attribute description
cursor string The cursor value for this delta.
object string The object type of the changed object. (message, thread, etc.)
id string The id of the changed object
event string The type of change. Either create, modify, or delete.
attributes The current state of the object. Note this may be different from the state when the delta change actually happened.

The delta for an object will condense changes to the latest version of the object since the requested cursor. This means that, if an object was modified and then deleted, only a delta representing the "delete"
event will be returned.

An example of a delta representing a deleted event is:

{
    "cursor": "3vp8q6xxsjn2tzp6xo044mcr8",
    "attributes": {
        "status": "cancelled",
        "account_id": "625549b7800djo0f346v9h541",
        "object": "event",
        "calendar_id": "1r4ay0of6d7dkcjgh12345678",
        "title": "MyDeletedEvent",
        ...
    },
    "object": "event",
    "event": "modify",
    "id": "1234thgv5u5r2r4u7u5ov5678"
}

For event objects that have been deleted, the event parameter will be set to “modify” and the status attribute set to “cancelled”, matching the semantics of the event objects.

Expanded Delta View

Request deltas from this cursor onward with expanded views

curl https://api.nylas.com/delta?cursor=aqb0llc2ioo0bclh7uxkim9z6&view=expanded

Adding view=expanded to the request expands thread and message objects in the response to include additional information.

Thread objects are expanded to contain message and draft sub-objects and will remove message_ids and draft_ids. Note the message and draft sub-objects do not include a body parameter.

Message objects are expanded to include several additional RFC2822 headers. For more details see the Expanded Message View.

Long-polling Delta Updates

Normally a request with the latest cursor will immediately return an empty list with no deltas. However, you can use the long-polling endpoint to instruct the server to hold open the request until either new changes are available, or a timeout occurs. This behavior can be used to provide real-time updates on platforms that do not support partial response parsing, such as web browsers.

method GET
endpoints https://api.nylas.com/delta/longpoll
authentication Access Token as HTTP Basic Auth username

URL Parameters:

attribute description
cursor string A cursor value saved from a previous response.
timeout integer A request timeout interval. Defaults to 120 seconds.

Streaming Delta Updates

Request deltas from this cursor onward

curl https://api.nylas.com/delta/streaming?cursor=aqb0llc2ioo0bclh7uxkim9z6

Request deltas from this cursor onward

cursor = inbox.get_cursor(1407543195)

last_cursor = nil
inbox.delta_stream(cursor) do |event, object|
    if event == "create" or event == "modify"
        puts "Got an update"
    end
end

Request deltas from this cursor onward
:::javascript

// Start the stream and add event handlers.
var stream = nylas.deltas.startStream(cursor);

stream.on('delta', function(delta) {
  // Handle the new delta here.
  if (delta.event == 'create' || delta.event == 'modify') {
    console.log('Got an update');
  }
}).on('error', function(err) {
  // Handle errors here, such as by restarting the stream at the last cursor.
  console.error('Delta streaming error:', err);
});

If you are building a server-side application where you can parse incoming data before a request has finished, then you should use the streaming delta endpoint, which allows you to process changes in real time without polling. This will start a HTTP connection that will return deltas starting from that cursor, and then keep the connection open and continue to stream new changes.

method GET
endpoints https://api.nylas.com/delta/streaming
authentication Access Token as HTTP Basic Auth username
attribute description
cursor string A cursor value saved from a previous response.

The body of a streaming API response consists of a series of newline-delimited messages, where “newline” is considered to be \n (in hex, 0x0A) and “message” is a JSON encoded delta object or a blank line.

If the connection is interrupted or needs to disconnect, your application can later issue a new request and simply pass in the cursor for the last delta it processed. This ensures that no changes are missed.

Filtered deltas

Request deltas that exclude messages and contacts

curl "https://api.nylas.com/delta/streaming?cursor=aqb0llc2ioo0bclh7uxkim9z6&exclude_types=message,contact"

Request deltas only for threads

curl "https://api.nylas.com/delta/streaming?cursor=aqb0llc2ioo0bclh7uxkim9z6&include_types=thread"

Request deltas that exclude messages and contacts

nylas.delta_stream(cursor, exclude=[Nylas::Contact,
                                    Nylas::Message]) do |event, object|
if event == 'create' or event == 'modify'
        puts object.subject
    end
end

Request deltas that exclude messages and contacts

excluded_types = ['contact', 'message']
var stream = nylas.deltas.startStream(cursor, excluded_types);

stream.on('delta', function(delta) {
  // Handle the new delta here.
  if (delta.event == 'create' || delta.event == 'modify') {
    console.log('Got an update');
  }
}).on('error', function(err) {
  // Handle errors here, such as by restarting the stream at the last cursor.
  console.error('Delta streaming error:', err);
});

The delta endpoint supports a modified version of filters, which allows applications to request only changes to a specific object type.

Optional URL parameters

attribute description
exclude_types string Comma-separated list of object types to exclude from returned deltas. Options are contact, event, file, message, draft, thread, folder, label.
include_types string Comma-separated list of the only object types to include in returned deltas. Options are contact, event, file, message, draft, thread, folder, label.

Note that specifying both exclude_types and include_types will result in an error.

Search

Searching messages for “Pinot Noir”

curl https://api.nylas.com/messages/search?q=Pinot+Noir

Response is a list of message objects.

The search sub-endpoint is used to run a full-text search that is proxied to the account’s provider. Results are matched with objects that have been synced, and are then returned.

method GET
endpoints https://api.nylas.com/messages/search
https://api.nylas.com/threads/search
authentication Access Token as HTTP Basic Auth username

Required URL Parameters:

attribute description
q string Search query

The search endpoint returns 40 results by default. This endpoint supports Pagination so your application can request more objects, or iterate through all results. For details on the query syntax for the most commmon providers, please see Google, Exchange/Outlook, Yahoo, and Generic IMAP.

Filters

Filters allow you to narrow a request based on specific parameters. Generally the more specific you can make the requests, the faster they perform, so it’s important to use filters whenever possible.

Filters may be appended to API requests on Messages, Threads, Files and Events. Note that values must use percent-encoding (also known as URL encoding). See the specific endpoint documentation for details on exact syntax and supported parameters.

Filters do not currently support wildcards, such as from=*@expedia.com. Providing multiple values for a single filter is also unsupported. If you’re looking for more generalized parameter matching, check out the Search APIs.

Pagination

Even though a user’s mailbox usually has thousands upon thousands of items, most Nylas API endpoints return a maximally fixed number of objects for performance reasons.

Your application can increase performance by including a limit parameter to request fewer objects. Using both the limit and offset parameters allows you to easily paginate through a large number of objects.

Note that if a request returns fewer objects than the limit parameter, there are no more items available to return.

URL Parameter Description
limit integer Number of objects to return. Often defaults to 100. If set too high, requests may fail to prevent excessively large response bodies.
offset integer Zero-based offset from default object sorting.

If you are building an application that intends to maintain a cache of the user’s data, such as a full-featured mail client, we recommend using the Deltas endpoint to avoid repeatedly paginating over all objects.

Views

Instead of returning all data about an object, the following views allow you to customize the response for any endpoint. They can be combined with filters. The following endpoints support view parameters: Threads, Messages, Drafts, Folders, Labels, Files, Calendars, Events, and Contacts

IDs

Example request for only the mesage IDs within a specifc thread

curl https://api.nylas.com/messages?thread_id=aqb0llc2ioo0bclh7uxkim9z6&view=ids

Response

[
   "f594seo6izjks2s7qxjbwquol",
   "3a95fq0askqgj7mnh6i281ahz",
   "4vfg8p1om177q2cfx9sselkea"
]

Return only the IDs of objects.

Supported by Threads, Messages, Drafts, Folders, Labels, Files, Calendars, Events, and Contacts.

Count

Example count view request

curl https://api.nylas.com/threads?in=inbox&view=count

Response

{
    "count": 386
}

Example count view request

puts nylas.threads.where(:in => 'inbox').count

Response

386

Example count view request

curl https://api.nylas.com/threads/<thread_id>?view=count

Return the number of objects in the collection being queried.

Supported by Threads, Messages, Drafts, Folders, Labels, Files, Calendars, Events, and Contacts.

Expanded

Expands threads response to contain message/draft sub-objects. Adding view=expanded will remove message_ids and draft_ids, and include messages and drafts. Note the message and draft sub-objects do not include a body parameter.

Message objects are expanded to include several additional RFC2822 headers. For more details see the Expanded Message View.

Supported by Threads, Messages, and Deltas.

Webhooks

Webhooks allow your application to receive notifications when certain events occur. For example, when a new email is received, Nylas will make a POST request to your URI endpoint letting you know information about the new message. You can specify what events you’d like to be notified about in the developer dashboard.

Creating a Webhook

Webhooks for an application are configured from the Nylas Developer Dashboard. To configure a new webhook, go to the “Webhooks” section of your application and select “Add Webhook”. You will need to provide:

  1. The full URI for the webhook. Since this is the endpoint the Nylas servers send notifications to, the URI must be accessible from the public internet for the webhook to work. It must be an HTTPS endpoint as well. The endpoint is verified by sending a verification request.

  2. The triggers to receive notifications for. The list of available triggers are:

Trigger Description
account.connected An account has been connected to your app
account.running An account is syncing and running properly
account.stopped An account was stopped or cancelled
account.invalid An account has invalid credentials and needs to re-authenticate
account.sync_error An account has a sync error and is no longer syncing
message.created A new message was sent or received
message.opened A tracked message has been opened by a message participant
message.link_clicked A link in a tracked message has been clicked by a message participant
thread.replied A participant replied to a tracked thread

You can create more than one webhook for your application; however, the webhook endpoints cannot be the same. For example, you may create a webhook to receive notifications for the message.created trigger, and another to receive notifications for the account.connected and account.stopped triggers, but the webhooks must have different callback URIs.

Verification Request

Example request sent by Nylas to your webhook endpoint

curl -X GET https://callmemaybe.com/nylas-webhook?challenge=6199oyu7yvuok4l9

How to handle Nylas’ verification request

@app.route('/webhook', methods=['GET'])
def index():
    if flask.request.method == 'GET' and 'challenge' in flask.request.args:
        return flask.request.args['challenge']

How to handle Nylas’ verification request

get '/webhook' do
  status 200
  params['challenge']
end

How to handle Nylas’ verification request

app.get('/webhook', function(req, res) {
  return res.status(200).send(req.query.challenge);
});

Nylas will check to make sure your webhook is valid by making a GET request to your endpoint with a challenge parameter when you add the endpoint to the developer dashboard (or anytime you set the webhook state to active). All you have to do is return the value of the challenge parameter in the body of the response. Make sure you aren’t returning anything other than the exact value of the challenge parameter. Your application has up to ten seconds to respond to the verification request. The verification request is not retried automatically.

Enabling and Disabling a Webhook

Webhooks are set to “active” by default. To disable a webhook, go to the Webhooks section of your application and change the webhook’s State to “inactive”.

Receiving Notifications

Once a webhook has been successfully created, Nylas will send an HTTPS POST request to the configured endpoint when an event of interest occurs. If multiple changes occur at the same time, they may be included in the same notification.

A request that times out or results in a non-HTTP 200 response code is retried once every 10 minutes, up to 60 times. Failing that, the webhook is retired and its state set to “failed”.

How to verify X-Nylas-Signature

import hmac
import hashlib
def verify_request(request):
  digest = hmac.new(NYLAS_CLIENT_SECRET, msg=request.data, digestmod=hashlib.sha256).hexdigest()
  return digest == request.headers.get('X-Nylas-Signature')

How to verify X-Nylas-Signature

def verify_request(data, signature)
  digest = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), NYLAS_CLIENT_SECRET, data)
  return Rack::Utils.secure_compare(digest, signature)
end

How to verify X-Nylas-Signature

const crypto = require('crypto');
function verify_nylas_request(req) {
  let digest = crypto.createHmac('sha256', config.nylasClientSecret).
                                 update(req.rawBody).
                                 digest('hex');
  return digest === req.get('x-nylas-signature')
}

Each request made by Nylas includes an X-Nylas-Signature header. The header contains the HMAC-SHA256 signature of the request body, using your client secret as the signing key. This allows your app to verify that the notification really came from Nylas.

The body of the request is in UTF-8 JSON format and contains details about the event.

Example notification sent by Nylas to webhook endpoint

{
    "deltas": [
    {
        "date": 1097829637,
        "type": "account.sync_error",
        "object": "account",
        "object_data": {
            "object": "account",
            "id":  "7ntawa6ltos76vz5hvphkp8k1",
            "namespace_id": "9y87sguhody79tgydisfsf",
            "account_id": "9y87sguhody79tgydisfsf"
        }
    },
    {
        "date": 1097829637,
        "type": "message.created",
        "object": "message",
        "object_data": {
            "object": "message",
            "id":  "vphkp8k17ntawa6ltos76vz5h",
            "attributes": {
              "thread_id": "13kjekf8jr94825mt7caav7t2",
              "received_date": 1476395195
            },
            "namespace_id": "9y87sguhody79tgydisfsf",
            "account_id": "9y87sguhody79tgydisfsf"
        }
    },
    {
        "date": 1471630848,
        "type": "message.link_clicked",
        "object": "metadata",
        "object_data": {
            "object": "metadata",
            "id": "NYLAS_METADATA_ID",
            "account_id": "EMAIL_ACCOUNT_ID",
            "metadata": {
                "sender_app_id": "SENDER_APP_ID",
                "link_data": [
                    {"url": "apple.com", "count": 2},
                    {"url": "apple.com", "count": 0},
                    {"url": "nylas.com", "count": 10},
                ],
                "payload": "hello world",
                "message_id": "NYLAS_MESSAGE_ID",
                "recents": [{
                  "id:" 0,
                  "ip": "0.0.0.0",
                  "user_agent": "chrome",
                  "link_index": 2
                }, ...]
            }
        }
    }]
}

Notification format

The webhook endpoint will receive a list of changes for the triggers specified while creating the webhook. Note that for security reasons, the actual changes are not included. Instead, the response contains the trigger type and object id for each change; you can retrieve the changed object with the corresponding /object API endpoints.

The body of the POST request is encoded as a UTF-8 JSON object with the following attributes:

Attribute Description
deltas array Array of delta objects

Each delta object has the following attributes:

Attribute Description
date unix timestamp Timestamp when the change occurred
type string The trigger for this notification
object string The changed object type
object_data object Contains the changed object’s object type, account_id, object id and an attributes sub-object

The attributes sub-object has extra information about the object. Currently, attributes is only included in object_data for message.created triggers.

Attribute Description
received_date unix timestamp Timestamp when the message was originally received
thread_id string The thread_id that this message belongs to

For more information about message tracking and the corresponding metadata
object type, see Message Tracking.

Message Tracking

The Nylas API offers several ways of tracking different types of actions that may happen to a message or thread. For example, it’s possible to detect when an email message has been opened by the recipient.

We’ll notify you when these actions occur by sending a webhook notification to your server. If you haven’t set up webhooks yet, click here. Make sure that you’ve enabled all the appropriate triggers you’d like to be notified about in your developer dashboard before sending a message with tracking enabled.

There are three different ways you can track a message or thread and you can use any combination of these tracking features together. All you have to do is include a tracking attribute when you send a message through the /send endpoint.

Enabling Tracking

Example curl request when directly sending a message that enables link and open tracking:

curl -X POST -H "Authorization: Basic yourBasicAuth" -d '{
    "reply_to_message_id": "84umizq7c4jtrew491brpa6iu",
    "body" : "Please click this: <a href='https://nylas.com/'>click</a>",
    "subject": "New Site",
    "to": [
        {
            "name": "Nylas",
            "email": "support@nylas.com"
        }
    ],
    "tracking": {
        "links": true,
        "opens": true,
        "thread_replies": false,           
        "payload": "Any string you want!!"
    }
}' "https://api.nylas.com/send"

To enable tracking for a message, include a tracking attribute alongside the other attributes when sending a message. You can include the tracking object when sending a draft or when sending directly.

The tracking object looks like this:

Attribute Description
links boolean True enables link tracking
opens boolean True enables message open tracking
thread_replies boolean True enables thread reply tracking
payload string An optional string that allows you to keep track of additional information. This string will be included in the webhook notification.

Understanding Tracking Notifications

Once a user performs an action on a message that you’ve enabled tracking for, like opening the message, Nylas will make a POST request to your webhook endpoint with delta information about the action that occurred.

object_data will contain a metadata sub-attribute that has information about the action. To see the more general structure of the webhook notification, click here.

More detailed information about each of the notifications and their specific metadata sub-attributes are below.

When you send a message with link tracking enabled you’ll be notified whenever any of the recipients click on tracked links in that message.

To enable link tracking for a message, set links to true in the tracking attribute when sending the message through the /send endpoint. See here for more information about creating the tracking attribute.

Behind the scenes, Nylas will rewrite all HTML links with a new URL that helps us track link clicks.

Example webhook delta for link clicked notification

{
    "deltas": [
    {
        "date": 1471630848,
        "type": "message.link_clicked",
        "object": "metadata",
        "object_data": {
            "object": "metadata",
            "id": "NYLAS_METADATA_ID",
            "account_id": "EMAIL_ACCOUNT_ID",
            "metadata": {
                "sender_app_id": "SENDER_APP_ID",
                "link_data": [
                    {"url": "apple.com", "count": 2},
                    {"url": "apple.com", "count": 0},
                    {"url": "nylas.com", "count": 10},
                ],
                "payload": "hello world",
                "message_id": "NYLAS_MESSAGE_ID",
                "recents": [{
                  "id:" 0, 
                  "ip": "0.0.0.0", 
                  "user_agent": "chrome", 
                  "link_index": 2
                }, ...]
            }
        }
    }
    ]
}

metadata is a sub-attribute of object-data

Attribute Description
sender_app_id string The sender’s Nylas application id
link_data array An array of objects with information about number of clicks per link
payload string An optional string that you can include when enabling tracking for the message to contain arbitrary data
message_id string Nylas message_id of the message
recents array An array of the most recent link-click events

link_data sub-attribute of metadata

Attribute Description
url The url that was clicked
count Number of times the url was clicked

recents sub-attribute of metadata

Attribute Description
id An ID unique to each message that increments with each click
ip IP address of the user that clicked the link
user_agent User agent of the user that clicked the link
link_index Corresponds to an entry in link_data

The recents field will have the last 50 events. These will have ids in order to help parse which events have already been processed. The id s are only unique within a particular recents array, and there is a separate recents array for each message/trigger pair. So, for example, opening message A, clicking on a link in message A, and opening message B will all have an id of 0. Opening message A again will have id 1.

Open Tracking

Example webhook delta for messaged opened notification

{
    "deltas": [
    {
        "date": 1471630848,
        "type": "message.opened",
        "object": "metadata",
        "object_data": {
            "object": "metadata",
            "id": "NYLAS_METADATA_ID",
            "account_id": "EMAIL_ACCOUNT_ID",
            "metadata": {
                "sender_app_id": "SENDER_APP_ID",
                "count": "OPEN_COUNT",
                "payload": "{myCustom: 'data'}",
                "message_id": "NYLAS_MESSAGE_ID",
                "recents": [{
                  "id:" 0, 
                  "ip": "0.0.0.0", 
                  "user_agent": "chrome"
                }, ...]
            },
        }
    }
    ]
}

When you send a message with open tracking enabled you’ll be notified whenever any of the recipients open that message.

To enable open tracking for a message, set opens to true in the tracking attribute when sending the message through the /send endpoint. See here for more information about creating the tracking attribute.

metadata is a sub-attribute of object-data

Attribute Description
sender_app_id The sender’s Nylas application id
count The number of times this message has been opened
payload An optional string that you can include when enabling tracking for the message to contain arbitrary data
message_id Nylas message_id of the message
recents An array of the most recent link-click events

Reply Tracking

Example webhook delta for thread reply notification

{
  "deltas": [
    {
        "date": 1471630848,
        "type": "thread.replied",
        "object": "metadata",
        "object_data": {
            "object": "metadata",
            "id": "NYLAS_METADATA_ID",
            "account_id": "EMAIL_ACCOUNT_ID",
            "metadata": {
                "sender_app_id": "VELOCIFY_APP_ID",
                "payload": "{myCustom: 'data'}",
                "message_id": "NYLAS_MESSAGE_ID",
                "reply_to_message_id": "NYLAS_REPLY_TO_MESSAGE_ID",
                "thread_id": "NYLAS_THREAD_ID",
                "from_self": true,
                "timestamp": 1471630848,
            },
        }
    }
  ]
}

When you send a message with reply tracking enabled you’ll be notified whenever any participant of the corresponding thread responds to that thread. message responds to the message.

To enable reply tracking for a message, set thread_replies to true in the tracking attribute when sending the message through the /send endpoint. See here for more information about creating the tracking attribute.

metadata is a sub-attribute of object-data

Attribute Description
sender_app_id The sender’s Nylas application id
payload An optional string that you can include when enabling tracking for the message to contain arbitrary data
message_id Nylas message_id of the new message
reply_to_message_id Nylas message_id of the message that the new message is replying to
thread_id Nylas thread_id
from_self Boolean that indicates whether the reply came from the account that enabled this tracking or not
timestamp Timestamp in UTC Unix seconds

Sync status



Account Sync Status

Sometimes, syncing cannot complete successfully. In the event of a recoverable failure, you will see a notification in your developer dashboard and one of the following status messages in the Accounts API:

Status Action required
running Sync is successfully running. No action required.
invalid-credentials Authenticating failure with mail server. You should prompt the user to re-authorize
config-error Configuration issue. Prompt the user to re-authorize and update configuration
connection-error Error connecting to backend provider. Wait.*
sync-error Error while syncing. Wait.*
stopped Syncing is stopped. Upgrade the account to start syncing

* Most sync and connection failures are temporary, but if this persists, check our status page for any known problems and/or contact support.

Credential errors

These occur when the user’s account fails authorization. Usually this is because the user has changed their password, revoked their OAuth credentials, or their IMAP/ SMTP or Exchange server endpoint has changed.

Without authorization, no mail operations can successfully complete. In order to make the account active again, you will need to re-authorize the user by asking them to reauthenticate by going through the authentication flow again.

Configuration problems

‘All Mail’ folder disabled

For Gmail and Google Apps accounts, the Nylas Sync Engine synchronizes the ‘All Mail’ folder. If a user has disabled IMAP access for this folder, synchronization will fail.

To fix it, the user needs to make sure the ‘All Mail’ folder has ‘Show in IMAP’ checked in their Gmail settings. After enabling it, re-authorize the user by restarting the authorization flow.

Full IMAP not enabled

As the Nylas Sync Engine synchronizes mail over IMAP, if IMAP access is not properly enabled for an account or a domain, synchronization will fail. This does not apply to Microsoft Exchange accounts.

The user needs to ensure IMAP is fully enabled for their account. This may involve contacting their domain administrator or hosting provider. Once it is enabled, re-authorize the user.

Connection and sync errors

If temporary connection issues persist, contact support for assistance. Outages or other unscheduled service interruptions are posted on Nylas Status.

Too many connections

Some IMAP configurations limit the number of connections which can be made. If a user has several programs accessing their email account via IMAP, they may run into this error with the Nylas Sync Engine. The resolution is for the user to close other programs which may be accessing their account via IMAP. Gmail users can check which applications they have authorized, and remove any that are no longer being used.

Rate limiting

We rate-limit API access on a per email account basis. Rate limits typically expire within 10-25 seconds depending on which endpoint you hit.

Scope Rate-limit Expiration
General 200 requests per endpoint over 10s 10s
Concurrent Streaming 10 concurrent requests per streaming endpoint 25s
Concurrent Queries 5 concurrent connections open to /messages or /threads 25s

If you need to request the messages or threads endpoint beyond what our rate limits allow, please contact support@nylas.com and we can chat about your particular use case.

Errors

Nylas uses conventional HTTP response codes to indicate the success or failure of an API request.

Status Code Description
200 OK Everything worked as expected.
400 Bad Request Malformed or missing a required parameter.
401 Unauthorized No valid API key provided.
402 Request Failed Parameters were valid but the request failed.
404 Not Found The requested item doesn’t exist.
405 Method Not Allowed You tried to access a resource with an invalid method.
410 Gone The requested resource has been removed from our servers.
418 I’m a teapot information_desk_person
429 Too Many Requests Slow down! (If you legitimately require this many requests, please contact support.)
500, 502,
503, 504 Server errors
An error occurred in the Nylas server. If this persists, please see our status page or contact support.

For a full list of possible codes, we recommend the Wikipedia article.

Error bodies includes a JSON object with a standard set of attributes, including an error_type and a human-readable message string. These are designed to make debugging easier and allow for different handling of scenarios that produce the same HTTP status code.

Error Type Details
api_error General API error
invalid_request_error The request provided has an invalid format

Supported Providers

Key Provider
gmail Gmail and Google Apps
eas Microsoft Exchange (ActiveSync) and Microsoft Office365
outlook Outlook.com (aka Hotmail)
yahoo Yahoo! Mail
icloud iCloud (aka MobileMe or DotMac)
custom A custom account syncing via generic IMAP

Other known IMAP providers:

Key Provider
aol AOL Mail
fastmail FastMail
gandi GandiMail
gmx GMX
mail.ru Mail.ru
yandex Yandex.Mail
godaddy GoDaddy Mail
hover Hover.com
namecheap Namecheap
bluehost Bluehost
soverin Soverin
zimbra Zimbra
123_reg 123-reg
126 126
qq, foxmail, qq_enterprise QQ Mail
aliyun Aliyun (Alibaba Group)
163, 163_ym, 163_qiye NetEase 163 (China)
yeah.net Yeah.net
139 139.com (China)

Deprecated providers:

Key Provider
_outlook IMAP-based Outlook.com (deprecated)

API Changelog

3/6/2017

1/10/2017

10/13/2016

10/4/2016

Still need help?

Feel free to send us an email or join our community Slack channel!

We’re happy to help you figure out everything from architectural decisions to deep-diving obscure bugs. raised_hands