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

Node SDK

The Node SDK Quickstart Guide

The Nylas Communications Platform allows developers to quickly build features that connect to every inbox, calendar, and contacts book in the world. The Nylas SDKs are the quickest way to integrate the Nylas Email, Calendar, and Contacts APIs into your app.

This guide will help you get started with the Nylas Node SDK.

Setup your developer account first!

Before following this guide, sign up for a Nylas developer account, and follow our guide to get your developer API keys.

Install

Before you install the SDK, sign up for a Nylas developer account, and follow our guide to get your developer API keys. You will need three values from this guide to run the code examples found here:

  • CLIENT_ID - The CLIENT ID found on the dashboard page for your Nylas App
  • CLIENT_SECRET - The CLIENT SECRET found on the dashboard page for your Nylas App
  • ACCESS_TOKEN - The Access token that is provided when you authenticate an account to your Nylas App

To run the Nylas Node SDK, you will first need to have Node and npm installed on your machine.

Then, head to the nearest command line and run the following:
npm install nylas

Alternatively, if you prefer to use Yarn, you can install the Nylas Node SDK with yarn add nylas

SDK Overview

Every resource (i.e., messages, events, contacts) is accessed via an instance of Nylas. Before making any requests, be sure to call config and initialize the Nylas instance with your clientId and clientSecret. Then, call with and pass it your accessToken. The accessToken allows Nylas to make requests for a given account's resources.

const Nylas = require('nylas');

Nylas.config({
  clientId: CLIENT_ID,
  clientSecret: CLIENT_SECRET,
});

const nylas = Nylas.with(ACCESS_TOKEN);

Every resource method accepts an optional callback as the last argument:

nylas.threads.list({}, (err, threads) => {
  console.log(threads.length);
});

Additionally, every resource method returns a promise, so you don't have to use callbacks if your code is promise-friendly. Here's an example using promises:

nylas.threads.list({}).then(threads => {
  console.log(threads.length);
});

And here's an example using async/await:

const getThreadCount = async nylas => {
  const threads = await nylas.threads.list({});
  return threads.length;
};

Quickstart Examples

Account Management

Create Nylas App Client For Account Management

A Nylas App client allows you to access and modify the Account Management endpoint, which lets you check the status of user accounts connected to your Nylas app and upgrade/downgrade them. To create an app client object, call config and initialize the Nylas instance with your clientId and clientSecret.

const Nylas = require('nylas');

Nylas.config({
    clientId: CLIENT_ID,
    clientSecret: CLIENT_SECRET,
});

// Return all accounts connected to your Nylas App.
Nylas.accounts.list().then(accounts => {
    for (let account of accounts) {
      console.log(
        `Email: ${account.emailAddress} | `,
        `Billing State: ${account.billingState} | `,
        `Sync State: ${account.syncState}`,
        `ID: ${account.id}  | `
      );
    }
  });

Create Nylas User Account Client

A Nylas account client object lets you access all email, calendar, and contacts functionality and data for a specific user account. To create an account client object, call config and initialize the Nylas instance with your clientId and clientSecret. Then, call with and pass your accessToken. The accessToken allows Nylas to make requests for a given account's resources.

const Nylas = require('nylas');

Nylas.config({
    clientId: CLIENT_ID,
    clientSecret: CLIENT_SECRET,
});

const nylas = Nylas.with(ACCESS_TOKEN);

nylas.account.get().then(account => {
    console.log(
    `Email: ${account.emailAddress} | `,
    `Provider: ${account.provider} | `,
    `Organization Unit: ${account.organizationUnit}`
    );
  });
Ready to Build Your Integration?

Read the API reference for the accounts endpoint to learn more about the information you can access for accounts.

Email API

The Nylas Email API makes it easy to integrate Gmail, Outlook, Microsoft Exchange, Office 365 and every other email service provider into your application, and it offers full Create, Read, Update, and Delete (CRUD) operations.

Messages and Threads

The Nylas Email API allows you to work with both messages and threads.

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.

Threads are first-class objects that represent a collection of messages. Messages are threaded together with a variety of heuristics to match the format of third-party accounts as close as possible.

View Email Messages and Threads

const Nylas = require('nylas');

Nylas.config({
    clientId: CLIENT_ID,
    clientSecret: CLIENT_SECRET,
});
  
const nylas = Nylas.with(ACCESS_TOKEN);

//Get the most recent message 
nylas.messages.first({in: 'inbox'}).then(message =>{
    console.log(message.subject);
    // Log the Nylas global ID for the message
    console.log(message.id);
    // Log the service provider ID of the message
    console.log(message.unread);
});

// Return the 10 most recent threads
nylas.threads.list({limit: 10}).then(threads =>{
    for (let thread of threads) {
        console.log(thread.subject);
      	console.log(thread.participants);
    }
});

// List the 5 most recent unread email threads
nylas.threads.list({unread: true, limit: 5}).then(threads =>{
    for (let thread of threads) {
        console.log(thread.subject);
    }
});


Ready to Build Your Email Integration?

View the API reference for messages and threads to learn more. You can also check out the email API quickstart guide to learn more about the functionality of the Nylas Email API.

Search Messages and Threads

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 then returned.

const Nylas = require('nylas');

Nylas.config({
    clientId: CLIENT_ID,
    clientSecret: CLIENT_SECRET,
});
  
const nylas = Nylas.with(ACCESS_TOKEN);

nylas.messages.search("from:swag@nylas.com").then(messages => {
    for (let message of messages) {
        console.log(message.subject);
    }  
});

nylas.threads.search("A really important thing").then(threads => {
    for (let thread of threads) {
        console.log(thread.subject);
    }
});
Ready to Build Your Email Integration?

View the API reference for messages and threads to learn more. You can also check out the email API quickstart guide to learn more about the functionality of the Nylas Email API.

Send an Email

const Nylas = require('nylas');

Nylas.config({
    clientId: CLIENT_ID,
    clientSecret: CLIENT_SECRET,
});
  
const nylas = Nylas.with(ACCESS_TOKEN);

const draft = nylas.drafts.build({
    subject: 'With Love, from Nylas',
    to: [{ name: 'My Nylas Friend', email: 'swag@nylas.com' }],
    body: 'This email was sent using the Nylas email API. Visit https://nylas.com for details.'
});

// Send the draft
draft.send().then(message => {
    console.log(`${message.id} was sent`);
});

Send Raw MIME

To send raw MIME, you can build a draft and, instead of providing the normal fields, pass the MIME in an object as rawMime.

To retrieve the raw MIME for an account's message, call getRaw on the message object, and the MIME will be returned in a promise.

const nylas = Nylas.with(ACCESS_TOKEN);

// Send a message with raw MIME
const draft = nylas.drafts.build({ rawMime }); // rawMIME should be a MIME-format string with headers and multipart message
draft.send().then(message => console.log(message));

// Retrieve raw MIME for a message
nylas.messages
  .first()
  .then(message => message.getRaw())
  .then(rawMessage => console.log(rawMessage));
Ready to Build Your Email Integration?

View the API reference for sending to learn more. You can also check out the email API quickstart guide to learn more about the functionality of the Nylas Email API.

Calendar API

The Nylas Calendar API acts as a layer of abstraction on top of all calendar providers. The Nylas calendar API offers full Create, Read, Update, and Delete (CRUD) operations for all major calendar providers, with just a few lines of code you can add full-featured scheduling & calendar sync to your application.

Read Calendars and Events

const Nylas = require('nylas');

Nylas.config({
    clientId: CLIENT_ID,
    clientSecret: CLIENT_SECRET,
});

const nylas = Nylas.with(ACCESS_TOKEN);

// Most user accounts have multiple calendars where events are stored
nylas.calendars.list().then(calendars => {
    for (let calendar of calendars) {
        // Print the name of each calendar, it's ID, and whether or not the calendar is read only
        console.log(`Name: ${calendar.name} | Description: ${calendar.description} | ID: ${calendar.id} | Read Only: ${calendar.readOnly}`);
    }
});

// Get the id of a calendar whose events we want to inspect.
const calendar = nylas.calendars.first()
// Return the 5 oldest events from a specified calendar and print their titles to the console.
nylas.events.list({calendar_id: calendar.id, limit: 10 }).then(events => {
    for (let event of events) {
        console.log(
            `Title: ${event.title} | `,
            `Description: ${event.description} | `,
          	`When: ${event.when} | `,
            `Participants: ${event.participants}`,
        );
    }
});
Ready to Build Your Calendar Integration?

Check out the API reference docs for calendars and events to learn more about the features of these endpoints. You can also take a look at the calendar API quickstart guide to learn more about the functionality of the Nylas calendar API.

Create an Event

const Nylas = require('nylas');

Nylas.config({
    clientId: CLIENT_ID,
    clientSecret: CLIENT_SECRET,
});

const nylas = Nylas.with(ACCESS_TOKEN);

const event = nylas.events.build({
    title: 'New Years Party!',
    // calendarID must be the ID for a calendar the user has write access to.
    calendarId: CALENDAR_ID,
    // Event times are set via UTC timestamps
    // This example creates an event on December 31, 2018
    when: { start_time: 1546290000, end_time: 1546300800 },

    // Participants are stored as an array of participant subobjects
    participants: [{ email: 'swag@nylas.com', name: 'My Nylas Friend' }],
    location: 'My House!'
  });

// Event notification emails are not sent by default
// Enable notify_participants to send an email notification to participants
event.save({ notify_participants: true }).then(event => {
    console.log(event);
});
Ready to Build Your Calendar Integration?

Check out the API reference docs for calendars and events to learn more about the features of these endpoints. You can also take a look at the calendar API quickstart guide to learn more about the functionality of the Nylas calendar API.

Contacts API

The Nylas contacts API connects address books and contact databases associated with user's email accounts directly into your application. It offers full Create, Read, Update, and Delete (CRUD) operations to perform bi-directional sync with contact data including addresses, email addresses, birthdays, job titles, and more.

Read Contact Information

const Nylas = require('nylas');

Nylas.config({
    clientId: CLIENT_ID,
    clientSecret: CLIENT_SECRET,
});

const nylas = Nylas.with(ACCESS_TOKEN);

// Print the first and last name, email address, and the ID of the first 10 contacts returned for the user's account
nylas.contacts.list({limit: 10}).then(contacts => {
    for (const contact of contacts) {
        console.log(`Name: ${contact.givenName} ${contact.surname} | Email: ${contact.emailAddresses[0]['email']} | ID: ${contact.id}`);
    }
});
Ready to Build Your Contacts Integration?

Check out the API reference docs for the contacts endpoint to learn more. You can also take a look at the contacts API quickstart guide to learn more about the functionality of the Nylas contacts API.

Create a New Contact

const Nylas = require('nylas');

Nylas.config({
    clientId: CLIENT_ID,
    clientSecret: CLIENT_SECRET,
});

const nylas = Nylas.with(ACCESS_TOKEN);

const contact = nylas.contacts.build({
    // The contact's given name is typically their first name, 
    // you can specify a last name with 'surname'
    givenName: "My Nylas Friend",
    notes: "Make sure to keep in touch!",

    // Email address 'type' must be either 'work' or 'personal'
    emailAddresses: [{type: 'work', email: 'swag@nylas.com'}],

    // Phone number type must be one of 'business', 'organization_main', 
    // 'mobile', 'assistant', 'business_fax', 'home_fax', 'radio', 'car', 'home', or 'pager'
    // Google labels 'business' phone numbers as the contact's Work phone number
    phoneNumbers: [{type: 'random', number: '(555) 555-5555'}],

    // Web page type must be one of 'homepage', 'profile', 'work', or 'blog'
    webPages: [{type: 'homepage', url: 'https://nylas.com'}]
});

contact.save().then( contact => {
    console.log(contact);
});
Ready to Build Your Contacts Integration?

Check out the API reference docs for the contacts endpoint to learn more. You can also take a look at the contacts API quickstart guide to learn more about the functionality of the Nylas contacts API.

Other Examples

Authentication

The Nylas REST API uses server-side (three-legged) OAuth, and the Node.js bindings provide convenience methods that simplify the OAuth process. For more information about authenticating users with Nylas, visit the API docs.

urlForAuthentication() takes in an options object, which must have a redirectURI property defined. Other supported, but optional, properties are:

  • loginHint - The user's email address, if known.
  • state - An arbitrary string that will be returned back as a query param in your redirectURI.
  • scopes - An array of which scopes you'd like to auth with. The Nylas API provides granular authentication scopes that empower users with control over what level of access your application has to their data. See supported Authentication Scopes for a full list of scopes and details behind the scopes. If omitted, defaults to all scopes.

Step 1: Redirect the user to Nylas

const Nylas = require('nylas');

Nylas.config({
  clientId: CLIENT_ID,
  clientSecret: CLIENT_SECRET,
});

router.get('/connect', (req, res, next) => {
  options = {
    redirectURI: 'http://localhost:3000/oauth/callback',
    scopes: ['email.read_only', 'email.send'],
  };
  res.redirect(Nylas.urlForAuthentication(options));
});

Step 2: Handle the Authentication Response

router.get('/oauth/callback', (req, res, next) => {
  if (req.query.code) {
    Nylas.exchangeCodeForToken(req.query.code).then(token => {
      // save the token to the current session, save it to the user model, etc.
    });
  } else if (req.query.error) {
    res.render('error', {
      message: req.query.reason,
      error: {
        status:
          'Please try authenticating again or use a different email account.',
        stack: '',
      },
    });
  }
});

Create and Update Webhooks

const Nylas = require('nylas');

Nylas.config({
  clientId: CLIENT_ID,
  clientSecret: CLIENT_SECRET,
});

// create a new webhook
const newWebhook = Nylas.webhooks.build({
  callbackUrl: 'https://wwww.myapp.com/webhook',
  state: 'active',
  triggers: ['event.created', 'event.updated'],
  });
newWebhook.save().then(webhook => console.log(webhook.id));

// get and update the state of an existing webhook
// note: a webhook's callbackUrl & triggers are not updateable, only its state.
Nylas.webhooks.find('existingWebhookId').then(existingWebhook => {
  existingWebhook.state = 'active';
  existingWebhook.save();
})

// delete an existing webhook
Nylas.webhooks.delete(existingWebhook);

Use the Delta Streaming API

const Nylas = require('nylas');

Nylas.config({
  clientId: CLIENT_ID,
  clientSecret: CLIENT_SECRET,
});

const DELTA_EXCLUDE_TYPES = ['contact', 'calendar', 'event', 'file', 'tag'];
const nylas = Nylas.with(ACCESS_TOKEN);

nylas.deltas.latestCursor((error, cursor) => {
  // Save inital cursor.
  persistCursor(cursor);

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

  stream
    .on('delta', delta => {
      // Handle the new delta.
      console.log('Received delta:', delta);
      // Save new cursor so this delta doesn't need to be re-fetched for future streams.
      persistCursor(delta.cursor);
    })
    .on('error', err => {
      // Handle errors here, such as by restarting the stream at the last cursor.
      console.error('Delta streaming error:', err);
    });

  // Closing the stream explicitly, if needed
  stopButton.addEventListener('click', () => {
    stream.close();
  });
});

Get IP Addresses to Whitelist

To obtain a dynamic list of IP addresses that Nylas might use to connect.

  const nylas = Nylas.with(ACCESS_TOKEN);
  // Get IP Addresses
  Nylas.accounts.first()
  .then(account => account.ipAddresses())
  .then(response => console.log(response));

Example Apps

There are example Express apps in the example directory of the SDK's GitHub repo that show demonstrate how to use Nylas webhook and authentication features.

To try them out, navigate to the appropriate directory and replace the Nylas client ID and client secret in app.js, or create a config.js file with your application's credentials.

Then, run:

npm install
npm start

or

yarn
yarn start

Additional Resources

Here are some additional resources for when you're ready to move on.

  • Introduce yourself to the Nylas Communications Platform with our getting started guide
  • Take a look at the quickstart guides for the Nylas Email, Calendar and Contacts APIs to explore the features of the Nylas Communication Platform.
  • Setup Postman to make it easy to explore the Nylas APIs.
  • When you're ready to start integrating the Nylas Communication Platform into your app, take a look at our app integration guide.
  • Finally, you can always take a look at the API reference to learn about how the Nylas APIs work.

Node SDK


The Node SDK Quickstart Guide

Suggested Edits are limited on API Reference Pages

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