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

Native Authentication

Native Authentication Guide

This guide outlines how you can set up Native Authentication with the Nylas APIs to connect mail accounts. At this point, you should have your Nylas organization and application set up, so you're ready to authenticate an account!

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":          "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"
    },
    "scopes":				 "email.read_only,calendar"
  }'
curl -X POST https://api.nylas.com/connect/authorize -d '{
  "client_id":     "nylas_client_id",
  "name":          "Erlich Bachman",
  "email_address": "erlich@aviato.com",
  "provider":      "exchange",
  "settings":      {
    "username": "erlich@aviato.com",
    "password": "makingtheworldabetterplace"
  },
  "scopes":			"email,calendar"
}'
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"
  },
  "scopes":				 "email,calendar"
}'
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
  },
  "scopes":				 "email,calendar"
}'
api_client = APIClient(app_id="nylas_client_id", app_secret="nylas_client_secret")
nylas_authorize_resp = URLObject(api_client.authentication_url("/redirect", scopes=["name", "email", "calendar", "contacts"]))


response_body = json.dumps({
    "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"
    }
})

endpoint = api_client.authentication_url("/authorize")
nylas_authorize_resp.add(
  	responses.POST,
  	endpoint,
  	content_type="application/json",
  	status=200,
  	body=response_body,
)

nylas_code = nylas_authorize_resp.json()["code"]
curl -X POST https://api.nylas.com/connect/authorize -d '{
	"client_id":     "nylas_client_id",
  "name":          "Erlich Bachman",
  "email_address": "erlich@aviato.com",
  "provider":      "office365",
  "settings":      {
  "microsoft_client_id":     "",
      "microsoft_client_secret": "",
      "microsoft_refresh_token": "",
      "redirect_uri":            "", # Redirect URI that the was originally used to get the refresh token
  },
  "scopes":	"email.read_only,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": "erlich@aviato.com",
  "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
},

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 should 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.

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 Scope Nylas Scope(s)
gmail.compose email.drafts, email.send
gmail.modify email.modify, email.send
gmail.labels email.folders_and_labels
gmail.metadata email.metadata
gmail.send email.send
gmail.readonly email.read_only
calendar calendar
calendar.readonly calendar.read_only
contacts contacts
contacts.readonly contacts.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.

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.

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_client_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 AutoDiscovery for 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": "the-client-id",
  "client_secret": "the-client-secret",
  "code": "the-code"
}'
# Exchange the authorization code for an access token
api_client = APIClient(
  	app.config["NYLAS_OAUTH_CLIENT_ID"], 
  	app.config["NYLAS_OAUTH_CLIENT_SECRET"]
)
code = request.args.get('code')
session['access_token'] = api_client.token_for_code(code)

nylas_access_token = nylas_token_resp.json()["access_token"]

# Great, we've connected Google to Nylas! In the process, Nylas gave us
# an OAuth access token, which we'll need in order to make API requests
# to Nylas in the future. We'll save that access token in the Flask session,
# so we can pick it up later and use it when we need it.
session["nylas_access_token"] = nylas_access_token

client = APIClient(
    app_id=app.config["NYLAS_OAUTH_CLIENT_ID"],
    app_secret=app.config["NYLAS_OAUTH_CLIENT_SECRET"],
    access_token=session["nylas_access_token"],
)
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}`)
      );
    });

Native Authentication


Suggested Edits are limited on API Reference Pages

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