Only show these results:

Node SDK

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.

Prerequisites

Before you can start using the Nylas Node.js SDK, make sure you have done the following:

  • Sign up for your developer account.
  • Get your developer keys. You need to have your:
    • 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 provided when you authenticate an account to your Nylas App.
  • Get Node.js installed on your machine.
  • Make sure you have npm or yarn.

Install the Nylas Node.js SDK

Run npm install nylas or yarn add nylas.

Congrats! You’re now ready to write code with the Nylas Node.js SDK.

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;
};

Initialize the API Client

There are 2 ways to initialize APIClient:

  • Nylas App
  • Individual user account

Create Nylas App Client

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}`
);
});

Learn More

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);
}
});

Learn More

View the API reference for messages and threads to learn more. You can also check out the Email API 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);
}
});

Learn More

View the API reference for messages and threads to learn more. You can also check out the Email API 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));

Learn More

View the API reference for sending to learn more. You can also check out the Email API 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}`,
);
}
});

Learn More

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);
});

Learn More

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 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}`);
}
});

Learn More

Check out the API reference docs for the contacts endpoint to learn more. You can also take a look at the Contacts API 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);
});

Learn More

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

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.