Only show these results:

Inbox Folders and Labels with Node.js

Learn how to manage inbox folders and labels with the Nylas Node SDK. Build your email integration in 15 minutes

Node Email Create

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

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.

Congratulations!

You’re now ready to write code with 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,
});

Be Careful with Secrets

Follow best practices 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 and 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. Keep in mind, 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.

const { Label } = require('nylas/lib/models/folder');

function checkLabel (label) {
if (label.displayName == labelName) {
labelToUpdate = label;
};
}
function createAndApplyLabel () {
if ( !labelToUpdate ) {
console.log(`Creating New Label: ${labelName}`)
labelToUpdate = new Label(nylas, {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() creates 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');
const { Label } = require('nylas/lib/models/folder');

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:/docs/api/#tag--Accounts
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 = new Label(nylas, {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 and Use Inbox Folders

Other than Gmail, all email providers, including Microsoft Outlook, Exchange, Office365, 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. However, 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');
const { default: Folder } = require('nylas/lib/models/folder');

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:/docs/api/#tag--Accounts
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 = new Folder(nylas, {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);
})
})
}

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.