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

Inbox Folders and Labels with Node.js

Node.js has grown to be the most popular framework in the world, primarily due to its efficiency for data-intensive real-time applications and the ability to use JavaScript across the entire web stack. The Nylas Email API makes it easy to create and modify email labels for your users' Gmail accounts, and to manage inbox folders for providers like Microsoft Outlook, Exchange, and Office365.

This guide explains how to use the Nylas Node SDK and Email API manage email inbox labels and folders with JavaScript. It covers the following steps:

  1. Set up your Nylas developer account and get your API keys
  2. Install the Nylas Node.js SDK
  3. View all labels and folders for an email account
  4. Create a Gmail label and apply it to an email message
  5. Create an inbox folder and use it to organize email threads
  6. Explore the Nylas Email API

👍

Create Your Free Developer Account

Ready to build your email integration? Create your Nylas developer account to get started.

Set up Your Developer Account

After signing up for your Nylas developer account, follow our guide to get your API keys and authorize your first email account. When you complete this guide, you will have three tokens that you need to run the code examples below:

  • 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

Install the Nylas Node.js SDK

Prerequisites

Install the SDK

Head to the nearest command line and run npm install nylas or yarn add nylas.

Congrats! You’re now ready to start using the Nylas Node.js SDK.

Create a Nylas API Client

At its core, the Nylas Communication Platform is an API client that interfaces with all of the major email providers. The Nylas object provides access to every resource in the Nylas Email API, so the first thing you need to do is to initialize it:

const Nylas = require('nylas');

Then, call the config function and pass the CLIENT_ID and CLIENT_SECRET from earlier in this guide, replacing the placeholders with your values.

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

🚧

Take care with your secrets

It’s not best practice to include secrets like this in your code. For increased security, store these values as environment variables.

Next, call .with() and pass it the ACCESS_TOKEN from earlier in this guide. This allows Nylas to access data for a specific user account.

const nylas = Nylas.with(ACCESS_TOKEN);

View Labels & Folders For an email Account

The following example logs the display_name and id for all labels a Gmail account contains.

nylas.account.get().then(account =>{
    if (account.organizationUnit == 'label') {
        nylas.labels.list({}).then(labels => {
            console.log("This account contains the following labels:")
            for (const label of labels) {
              console.log(`Name: ${label.displayName} | ID: ${label.id}`);
            }
          });
    }
});

Let’s break this example down.

Gmail uses labels to organize email inboxes, which is different from most other email providers, which follow the practice of using folders to keep track of mailbox content. Nylas makes it easy to detect the organization method an account uses by providing an organizationUnit on the account, which returns either folder or label. In this example, if (account.organizationUnit == 'label') checks to see if the account uses labels before proceeding. Take a look at the API reference for the Account endpoint to learn more.

Then, nylas.labels.list({}) returns all the labels the account has. Some providers include a few default labels, including Inbox, Important, Trash, Spam, and more; this command also returns any custom labels the user has created. Finally, label.displayName and label.id are attributes the labels endpoint returns, and this example logs them to the console. Check out the API reference for the labels endpoint to learn more about what it returns, or you can view the API reference for folders to learn about how to work with inboxes that use folders.

Now, let's do the same thing for an account with folders:

if (account.organizationUnit == 'folder') {
        nylas.folders.list({}).then(folders => {
            console.log("This account contains the following folders:")
            for (const folder of folders) {
              console.log(`Name: ${folder.displayName} | ID: ${folder.id}`);
            }
          });

This example mostly mirrors the example for labels, but note that it checks for accounts where the organization_unit is folder, and it uses nylas.folders.list({}) to return the inbox folders the account has.

For convenience, here is the entire code example to read email labels and folders from an inbox.

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

nylas.account.get().then(account =>{
    if (account.organizationUnit == 'label') {
        nylas.labels.list({}).then(labels => {
            console.log("This account contains the following labels:")
            for (const label of labels) {
              console.log(`Name: ${label.displayName} | ID: ${label.id}`);
            }
          });
    }

    if (account.organizationUnit == 'folder') {
        nylas.folders.list({}).then(folders => {
            console.log("This account contains the following folders:")
            for (const folder of folders) {
              console.log(`Name: ${folder.displayName} | ID: ${folder.id}`);
            }
          }); 
    }
});

Create a Gmail Label and Apply it to an Email

Now, let's learn how to create labels in Gmail and apply them to emails. First, define a name to use for the new label. We also need to define labelToUpdate to be used later, but don’t worry about it for now.

const labelName = 'Cat Pics!';
let labelToUpdate;

Next, check the account endpoint, which returns either folder or label in the organizationUnit field. This code proceeds only if label is the unit for the account.

nylas.account.get().then(account => {
    if (account.organizationUnit == 'label') {
      nylas.labels.forEach({}, checkLabel, createAndApplyLabel);
    }
});

Then, it executes a few functions to check if a label with the same name we defined already exists, creates a new label if it doesn’t, and applies it to the most recent email. These functions are covered next.

The next example includes two functions. The first checks if a label exists with the name provided earlier. The second function creates the label if it doesn’t exist and applies it to the most recent email.

function checkLabel (label) {
    if (label.displayName == labelName) {
        labelToUpdate = label;
    };
}
function createAndApplyLabel () {
    if ( !labelToUpdate ) {
        console.log(`Creating New Label: ${labelName}`)
        labelToUpdate = nylas.labels.build({displayName: labelName});
        labelToUpdate.save().then(label => {
            addLabelToMostRecentMessage(label);
        });
    } else {
        console.log(`${labelName} already exists!`)
        addLabelToMostRecentMessage(labelToUpdate);
    }
}

The checkLabel (label) function uses label.displayName to return the name that is displayed for the label in user interfaces; this is used to compare to the name that was defined earlier.

After checking to make sure the label we want doesn’t already exist, createAndApplyLabel() invokes nylas.labels.build() to create a new label, providing the name we defined earlier for the required displayName attribute. Then, .save() is used to save the changes to Gmail. Take a look at the API reference for labels to learn more about creating labels.

Finally, this example calls addLabelToMostRecentMessage() to apply the label to the most recent email:

function addLabelToMostRecentMessage (label) {
    nylas.messages.first().then(msg => {
      msg.labels.push(label);
      console.log(`${label.displayName} applied to the most recent email.`)
      msg.save().then(savedMsg => {
        console.log(`Subject: ${savedMsg.subject}`);
        console.log("This email contains the following labels")
        console.log(savedMsg.labels);
      })
    })
}

This function uses nylas.messages.first() to get the most recent email from the inbox. Then, it invokes .push(), providing the label as an argument, to add the label to the message, and uses .save() to save this change to the Gmail account. Finally it logs the subject line and all labels that have been applied to the message to the console. Take a look at the API reference for messages to learn more about the features this endpoint provides.

Here is the entire code example to create a Gmail label and apply it to the most recent email.

const Nylas = require('nylas');
Nylas.config({
    clientId: CLIENT_ID,
    clientSecret: CLIENT_SECRET,
});
const nylas = Nylas.with(ACCESS_TOKEN);
// Assign a string to use for the display name of the new label
const labelName = 'Cat Pics!';
let labelToUpdate;

nylas.account.get().then(account => {
    // Gmail is the only email provider that uses labels, most providers use folders instead.
    // account.organizationUnit will return 'label' or 'folder' depending on provider capabilities
    // Account object reference: https://docs.nylas.com/reference#account
    if (account.organizationUnit == 'label') {
      nylas.labels.forEach({}, checkLabel, createAndApplyLabel);
    }
  });

function checkLabel (label) {
    if (label.displayName == labelName) {
        labelToUpdate = label;
    };
}

function createAndApplyLabel () {
    // Make sure that we aren't duplicating an existing label name
    if ( !labelToUpdate ) {
        // If the label doesn't exist, create it and pass it to the function that assigns it to the most recent email
        console.log(`Creating New Label: ${labelName}`)
        labelToUpdate = nylas.labels.build({displayName: labelName});
        labelToUpdate.save().then(label => {
            addLabelToMostRecentMessage(label);
        });
    } else {
        // If the label already exists, pass it to the function that assigns it to the most recent email
        console.log(`${labelName} already exists!`)
        addLabelToMostRecentMessage(labelToUpdate);
    }
}

function addLabelToMostRecentMessage (label) {
    nylas.messages.first().then(msg => {
      console.log(`${label.displayName} applied to the most recent email.`)
      // Add the label to the most recent email and save it.
      msg.labels.push(label);
      msg.save().then(savedMsg => {
        console.log(`Subject: ${savedMsg.subject}`);
        //Gmail includes a number of default labels,
        // including Inbox, Important, Trash, Spam, and more
        console.log("This email contains the following labels")
        console.log(savedMsg.labels);
      })
    })
}

Create & Use Inbox Folders

All email providers other than Gmail, including Microsoft Outlook, Exchange, Offic365, and Yahoo use folders to organize inbox content. Here is an example that illustrates the same functionality above, but with an inbox that uses folders. The syntax is mostly the same, but note that you can only use a single folder per email, and only threads can be put into folders. For more information about working with threads, take a look at the API reference for the Threads endpoint.

const Nylas = require('nylas');
Nylas.config({
    clientId: CLIENT_ID,
    clientSecret: CLIENT_SECRET,
});
const nylas = Nylas.with(ACCESS_TOKEN);
// Assign a string to use for the display name of the new folder
const folderName = 'Cat Pics!';
let folderToUpdate;

nylas.account.get().then(account => {
    // All providers, other than Gmail, use folders to organize email inbox content
    // account.organizationUnit will return 'label' or 'folder' depending on provider capabilities
    // Account object reference: https://docs.nylas.com/reference#account
    if (account.organizationUnit == 'folder') {
      nylas.folders.forEach({}, checkFolder, createAndUseFolder);
    }
  });

function checkFolder (folder) {
    if (folder.displayName == folderName) {
        folderToUpdate = folder;
    };
}

function createAndUseFolder () {
    // Make sure we aren't duplicating an existing folder name
    if ( !folderToUpdate ) {
        // If the folder doesn't exist, create it and pass it to our next function that moves an email thread into it
        console.log(`Creating New Folder: ${folderName}`)
        folderToUpdate = nylas.folders.build({displayName: folderName});
        folderToUpdate.save().then(folder => {
            moveMostRecentThreadToFolder(folder);
        });
    } else {
        // If the folder already exists, pass it to the function that assigns it to the most recent email
        console.log(`${folderName} already exists!`)
        moveMostRecentThreadToFolder(folderToUpdate);
    }
}

function moveMostRecentThreadToFolder (folder) {
    nylas.threads.first().then(thread => {
      // Add the folder to the most recent email and save it.
      thread.folders = folderToUpdate;
      thread.save().then(savedThread => {
        console.log(`Subject: ${savedThread.subject}`);
        console.log(`The most recent email has been moved to ${folder.displayName}`)
        console.log(savedThread.folders);
      })
    })
}
Ready to Build Your Email Integration?

Explore the Nylas Email API

If you’ve made it this far, congrats, you’ve used the Nylas Email API to work with inbox folders and labels! 🎉 There is plenty more that you can do with it: take a look at the following resources to learn more about the Nylas Communications Platform capabilities.

Updated 3 months ago

Inbox Folders and Labels with Node.js


Suggested Edits are limited on API Reference Pages

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