Nylas Docs

The Nylas Developer Hub

Welcome to the Nylas developer hub. You'll find comprehensive guides and documentation to help you start working with Nylas as quickly as possible, as well as support if you get stuck. Let's jump right in!

Developer Guide

Nylas Native Auth

Native Authentication Guide

This guide outlines how you can set up Native Authentication with the Nylas APIs to connect mail accounts. Native authentication is for developers who want to completely whitelabel the login experience through Nylas to match their application. If you haven't done so already, please complete our guide to get your developer API keys. you will need your Nylas application client ID and client secret to complete a native auth flow.

At this point, you should have your Nylas organization and application set up, so you're ready to authenticate an account!

🚧

Native Auth Vs. Hosted Auth

Native authentication allows you to build a highly-customizable login experience and is intended for developers who want a purely white-labeled experience for their customers. If you're looking for the quickest way to set up authentication, take a look at Nylas hosted authentication.

There are two steps to get an access_token for an account using Native Authentication:

  1. https://api.nylas.com/connect/authorize for authorizing a mailbox. See /connect/authorize reference for details.
  2. https://api.nylas.com/connect/token for retrieving an access_token for this account that can be used to query data from the Nylas API. See /connect/token reference for details.

Authorizing an account with /connect/authorize

The first step requires authorizing the account by POSTing to /connect/authorize. This endpoint is where your application sends mailbox credentials to verify they are correct. This begins the connection process.

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.

You'll need to include the following info in your request:

  • client_id - Your Nylas Application's client_id
  • name - The name of the user
  • email_address - The email address of the user
  • provider - One of gmail, yahoo, exchange, outlook, imap, office365, icloud, hotmail, or aol. Note that the format of the settings object below is dependent upon this field.
  • settings - An object dependent on the provider to which you are connecting. See "Provider Specific Settings" below for more details about this object.
  • scopes - Any combination of supported authentication scopes.
  • reauth_account_id - An optional existing account ID to re-authenticate. This is useful if the account has invalid credentials.

Here are some example requests for different provider objects to /connect/authorize.

curl -X POST https://api.nylas.com/connect/authorize -d '{ 
    "client_id": "nylas_client_id",
    "name": "Nyla The Cheetah",
    "email_address": "[email protected]",
    "provider": "gmail",
    "settings": {
        "google_client_id": "{google_api_client_id}",
        "google_client_secret": "{google_api_client_secret}",
        "google_refresh_token": "{google_api_refresh_token}"
    },
    "scopes": "email.read_only,calendar.read_only,contacts.read_only"
  }'
curl -X POST https://api.nylas.com/connect/authorize -d '{
    "client_id": "nylas_client_id",
    "name": "Nyla the Cheetah",
    "email_address": "[email protected]",
    "provider": "exchange",
    "settings": {
        "username": "[email protected]",
        "password": "MakeEmailSuckLess",
        "eas_server_host": "exchange.nylas.com"
    },
    "scopes": "email.read_only,calendar.read_only,contacts.read_only"
}'
curl -X POST https://api.nylas.com/connect/authorize -d '{
  "client_id": "nylas_client_id",
  "name": "Nyla The Cheetah",
  "email_address": "[email protected]",
  "provider": "aol",
  "settings": {
    "password": "MakeEmailSuckLess"
  },
  "scopes": "email.read_only,calendar.read_only,contacts.read_only"
}'
curl -X POST https://api.nylas.com/connect/authorize -d '{
    "client_id": "nylas_client_id",
    "name": "Nyla the Cheeta",
    "email_address": "[email protected]",
    "provider": "imap",
    "settings": {
        "imap_host": "imap.nylas.com",
        "imap_port": 12345,
        "imap_username": "nyla",
        "imap_password": "MakeEmailSuckLess",
        "smtp_host": "smtp.nylas.net",
        "smtp_port": 12346,
        "smtp_username": "nyla",
        "smtp_password": "MakeEmailSuckLess",
        "ssl_required": true
    },
    "scopes": "email.read_only,calendar.read_only,contacts.read_only"
}'
from nylas import APIClient
import requests

# Create a client that has access to your Nylas app.
nylas = APIClient(
    CLIENT_ID,
    CLIENT_SECRET
)

# Authenticate Gmail Accounts
gmail_authentication = {
    # Example: https://github.com/nylas/nylas-python/tree/master/examples/native-authentication-gmail
    "client_id": CLIENT_ID,
    "name":          "Nyla The Cheetah",
    "email_address": "[email protected]",
    "provider":      "gmail",
    "settings":      {  # See the Example above to learn more about these values
      "google_client_id":     "{google_api_client_id}",
      "google_client_secret": "{google_api_client_secret}",
      "google_refresh_token": "{google_api_refresh_token}"
    },
    "scopes": "email,calendar,contacts"
}

# Post the authentication payload to Nylas.
nylas_authorization = requests.post(
        "https://api.nylas.com/connect/authorize", json=gmail_authentication
)

# This code can be exchanged for an account access token
nylas_code = nylas_authorization.json()["code"]

# -------------------------------------------
# The remainder contains examples of how to authenticate other types of accounts

# Authenticate Exchange Accounts
exchange_authentication = {
    # Example: https://github.com/nylas/nylas-python/tree/master/examples/native-authentication-exchange
    "client_id": CLIENT_ID,
    "name":          "Nyla The Cheetah",
    "email_address": "[email protected]s.com",
    "provider":      "exchange",
    "settings": {
        "username": "[email protected]_server.com",
        "password": "MakeEmailSuckLess",
        "eas_server_host": "exchange.your_server.com"
    },
    "scopes": "email,calendar,contacts"
}

# Authenticate an Outlook Account
outlook_authentication = {
    "client_id": CLIENT_ID,
    "name":          "Nyla The Cheetah",
    "email_address": "[email protected]",
    "provider": "outlook",
    "settings": { # Uses the same format as Exchange Servers
        "username": "[email protected]",
        "password": "MakeEmailSuckLess",
        "eas_server_host": "outlook.com"

    },
    "scopes": "email,calendar,contacts"
}

# Authenticate an account from a known IMAP provider
known_imap_authentication = {
    "client_id": CLIENT_ID,
    "name":          "Nyla The Cheetah",
    "email_address": "[email protected]",
    "provider": "yahoo",  # can also be aol, icloud, or hotmail
    "settings": {
        "password": "MakeEmailSuckLess"
    },
    "scopes": "email,calendar,contacts"
}

# Authenticate any other IMAP account
generic_imap_authentication = {
    "client_id": CLIENT_ID,
    "name": "Nyla The Cheetah",
    "email_address": "[email protected]",
    "provider": "imap",
    "settings":      {
        "imap_host":     "imap.nylas.com",
        "imap_port":     12345,
        "imap_username": "nyla",
        "imap_password": "MakeEmailSuckLess",
        "smtp_host":     "smtp.nylas.net",
        "smtp_port":     12346,
        "smtp_username": "nyla",
        "smtp_password": "MakeEmailSuckLess",
        "ssl_required":  'true'
    },
    "scopes": "email,calendar,contacts"
}
curl -X POST https://api.nylas.com/connect/authorize -d '{ 
    "client_id": "nylas_client_id",
    "name": "Nyla The Cheetah",
    "email_address": "[email protected]",
    "provider": "office365",
    "settings":{
        "microsoft_client_id": "{microsoft_client_id}",
        "microsoft_client_secret": "{microsoft_client_secret}",
        "microsoft_refresh_token": "{microsoft_refresh_token}",
        "redirect_uri": "https://example.com/redirect", # Redirect URI that the was originally used to get the refresh token        
    },
    "scopes": "email.read_only,calendar.read_only,contacts.read_only"
  }'
curl -X POST https://api.nylas.com/connect/authorize -d '{
    "client_id": "nylas_client_id",
    "name": "Nyla the Cheetah",
    "email_address": "[email protected]",
    "provider": "outlook",
    "settings": {
        "username": "[email protected]",
        "password": "MakeEmailSuckLess",
        "eas_server_host": "eas.outlook.com"
    },
    "scopes": "email.read_only,calendar.read_only,contacts.read_only"
}'
curl -X POST https://api.nylas.com/connect/authorize -d '{
    "client_id": "nylas_client_id",
    "name": "Nyla the Cheetah",
    "email_address": "[email protected]", # Account to be authenticated
    "provider": "gmail",
    "settings": {
        "service_account_json": { # Service account credentials
        "type": "service_account",
        "project_id": "my-google-app-123456",
        "private_key_id": "68915b4e55baac9191dd32e0be784687c6873b14",
        "private_key": "-----BEGIN PRIVATE KEY-----\nMIIE....fZ1F8=\n-----END PRIVATE KEY-----\n",
        "client_email": "[email protected]m",
        "client_id": "10569134234239528168761",
        "auth_uri": "https://accounts.google.com/o/oauth2/auth",
        "token_uri": "https://oauth2.googleapis.com/token",
        "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
        "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/test-service-account%40my-google-app-123456.iam.gserviceaccount.com"
    }
    "scopes": "calendar"
}'
curl -X POST https://api.nylas.com/connect/authorize -d '{ 
  "client_id":     "nylas_client_id",
  "name":          "Joe User",
  "email_address": "[email protected]",    # Account to impersonate
  "provider":      "exchange",
  "settings":      {
        "microsoft_client_id":      "",
        "microsoft_client_secret":  "",
        "microsoft_refresh_token":  "",   # Service account refresh token!
        "redirect_uri":             "",
        "service_account": true
  },
  "scopes":                 "calendar"
}'

If the authorization is successful, you'll receive a code in the response's body. You'll be using this code in your next request.

{"code": "the response code"}

Provider Specific Settings

Depending on the provider body parameter you include you'll need to send a different settings object in your request to /connect/authorize. Here are the four possible settings objects you might need to include.

"settings": {
  "google_client_id":     "google_api_client_id",
  "google_client_secret": "google_api_client_secret",
  "google_refresh_token": "google_api_refresh_token"
}
"settings": {
  "username": "[email protected]",
  "password": "makingtheworldabetterplace",
  "eas_server_host": "exchange.aviato.com",
}
"settings": {
    "password": "makingtheworldabetterplace"
}
"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
}
"settings": {
  "microsoft_client_id":      "",
  "microsoft_client_secret":    "",
  "microsoft_refresh_token":    "",
  "redirect_uri":             "", # Redirect URI that the was originally used to get the refresh token
},
"settings": {
        "username": "[email protected]",
        "password": "MakeEmailSuckLess",
        "eas_server_host": "outlook.com"
  }
# Using OAuth authentication
"settings": {
  "microsoft_client_id":      "",
  "microsoft_client_secret":    "",
  "microsoft_refresh_token":    "",
  "redirect_uri":             "", # Redirect URI that the was originally used to get the refresh token
  "service_account": true
}

# Using password authentication
"settings": {
  "username": "[email protected]",
  "password": "serviceaccountpassword",
  "service_account": true
}
"settings": {
    "service_account_json": {
    "type": "service_account",
    "project_id": "metal-figure-239116",
    "private_key_id": "68ac9191dd3468915b4e52e0be785ba7c6873b14",
    "private_key": "-----BEGIN PRIVATE KEY-----\nMI...J7tF8=\n-----END PRIVATE KEY-----\n",
    "client_email": "[email protected]",
    "client_id": "105691998485416876281",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://oauth2.googleapis.com/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/test-service-account%40metal-figure-239116.iam.gserviceaccount.com"
  }
}

Google settings and setup for native authentication

If you plan on syncing Google accounts with your application, you need three pieces of information before you can authorize it through Nylas’ Native Authentication APIs.

First is the Google client_id and client_secret that you receive after creating your Google Project 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.

→ See Native Authentication Setup for Google OAuth to get your Google credentials.
→ Optionally, see Service Accounts Setup if your customers prefer users to be authenticated in bulk.

This guide doesn’t cover how to get a refresh_token, but to learn more about general OAuth setup, follow Google’s guide. You can also reference Google's documentation while working through this guide as needed.

We also have some example apps within our official SDKs that outline how to retrieve a refresh_token for Google accounts. See our Python, Ruby, and Node.js examples.

When you redirect your user to get a google refresh_token, please be sure that you request the right scopes from Nylas. Here's a mapping between Google scopes and Nylas scopes.

Google ScopeNylas Scope(s)
gmail.composeemail.drafts, email.send
gmail.modifyemail.modify, email.send
gmail.labelsemail.folders_and_labels
gmail.metadataemail.metadata
gmail.sendemail.send
gmail.readonlyemail.read_only
calendar + eventscalendar
calendar.readonly + events.readonlycalendar.read_only
contactscontacts
contacts.readonlycontacts.read_only

So for example, if your consent screen supports gmail.modify, and you request this scope when authenticating a user with Google, you'll need to pass email.modify and email.send scopes during the request to /connect/authorize.

📘

Include base OAuth scopes in your request to Google

Google OAuth projects include the scopes email (https://www.googleapis.com/auth/userinfo.email), profile (https://www.googleapis.com/auth/userinfo.profile), and openid by default. These are base scopes that grant access to information about the user. Nylas requires these scopes in order to validate the refresh token, so be sure to include them in your request to Google.

Also be sure to set the provider attribute to gmail when authenticating. See the "Google Account Example" in the code snippets table above.

Office365 settings and setup for native authentication

In order to sync Office365 accounts using OAuth rather than password based login you'll need to set up a Microsoft Azure account and related Microsoft developer application.

→ See Office365 OAuth Setup to set this up and get your O365 credentials.
→ Optionally, see Service Accounts Setup if your customers prefer users to be authenticated in bulk.

You'll need to keep track of some information from the OAuth flow with Microsoft in order to authenticate the account to Nylas. You'll get this info when you first authenticate an account through Microsoft's OAuth 2.0 flow. We recommend following Microsoft's guide for OAuth 2.0 authorization code flow.

🚧

Required settings

You'll need to make sure you're setting two values, tenant and scope, properly when you first authenticate an Office365 account directly with Microsoft.

  1. Set tenant to common
  2. Set scope to offline_access https://outlook.office365.com/EAS.AccessAsUser.All https://outlook.office365.com/EWS.AccessAsUser.All openid profile User.Read

For more info about tenant and scope please see Microsoft's guide for OAuth 2.0.

After you've authenticated the user through Microsoft's OAuth 2.0 flow, you'll need to pass the following info in the settings object to Nylas when calling /connect/authorize: microsoft_client_id, microsoft_client_secret, microsoft_refresh_token, and redirect_uri.

Please see the "Provider Specific Settings" above in the "Office365" tab for an example.

Microsoft Exchange ActiveSync additional settings

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

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

Known IMAP providers

You probably noticed that the only field you need to include in the settings object for known IMAP providers is a password. Nylas makes it easy to authenticate to common providers by passing along other IMAP connection info automatically.

You'll only need to include a password in the settings object for these known providers: yahoo, icloud, hotmail, and aol.

If your user has their own IMAP server, you'll need to provide the full settings object listed in the IMAP Provider example above.

Other IMAP Providers

Your user can also connect a regular IMAP and SMTP account by specifying the full connection settings in the settings object. Some are optional and default to a standard value. See the IMAP Provider example above for a code sample.

IMAP and SMTP servers are currently authenticated using username and password based login authentication.

👍

Success

At this point you've successfully retrieved your token from /connect/authorize. Good work!

Getting an access_token with /connect/token

This endpoint is where your application exchanges the code received from /connect/authorize and receives an access_token. This associates the mailbox with your Nylas Application.

You'll need to include the following info in your request to /connect/token:

  • client_id - Your Nylas Application's client_id
  • client_secret - Your Nylas Application's client_secret
  • code - The code from /connect/authorize
curl -X POST "https://api.nylas.com/connect/token" -d '{
  "client_id": "{client-id}",
  "client_secret": "{client-secret}",
  "code": "{code}"
}'
from nylas import APIClient

# Create a client that has access to your Nylas app.
nylas_app = APIClient(
    CLIENT_ID,
    CLIENT_SECRET
)

# Get an access token that grants access to user data and functionality.
# You need to generate a one-time-use code via Nylas to pass to this function.
# See: https://docs.nylas.com/reference#connectauthorize
ACCESS_TOKEN = nylas_app.token_for_code('{code_from_nylas}')

nylas = APIClient(
    CLIENT_ID,
    CLIENT_SECRET,
    ACCESS_TOKEN
)

# Now you have a Nylas client object that has access to user data and functionality
print(nylas.account)
auth_hash = env['omniauth.auth']

nylas_token = api.authenticate(name: auth_hash[:info][:name], 
    email_address: auth_hash[:info][:email], 
    provider: :gmail, settings:
    { 
      google_client_id: ENV['GOOGLE_CLIENT_ID'],
      google_client_secret: ENV['GOOGLE_CLIENT_SECRET'],
      google_refresh_token: auth_hash[:credentials][:refresh_token] })

api_as_user = api.as(nylas_token)
// First POST to /connect/authorize to get an authorization code from Nylas
// Then post to /connect/token to get an access_token that can be used to access
// account data
  return nylasCode(data)
    .then(code => {
      const params = {
        client_id: config.nylasClientId,
        client_secret: config.nylasClientSecret,
        code: code,
      };
      return nylasToken(params)
        .then(token => {
          return Promise.resolve(token);
        })
        .catch(err => {
          return Promise.reject(
            new Error(`Could not connect to Nylas. Error: ${err.message}`)
          );
        });
    })
    .catch(err => {
      return Promise.reject(
        new Error(`Could not connect to Nylas. Error: ${err.message}`)
      );
    });

Updated 21 days ago


Nylas Native Auth


Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.