Only show these results:

Manage labels and folders with the Nylas Node.js SDK

The Nylas Node.js SDK and the Email API enable you to manage labels for Gmail accounts and inbox folders for various providers, including Outlook, Exchange, and Office365.

This page discusses how to use the Nylas Node.js SDK and Email API to manage inbox labels and folders.

What you'll learn

In this tutorial, you'll learn how to do the following tasks:

  • View all labels or folders for an email account.
  • Create a Gmail label and apply it to an email message.
  • Create an inbox folder to organize email messages.

Prerequisites

Before you start, install the Nylas Node.js SDK and set up your environment:

Step 1: Initialize the Nylas object

At its core, the Nylas 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 API. Before you make any API requests, you must initialize the Nylas object with your client ID, client secret, and access token:

  1. Call the .config() function and pass your <CLIENT_ID> and <CLIENT_SECRET>.
  2. Call the .with() function and pass your <ACCESS_TOKEN>.

All together, your code should look like the example below.

const Nylas = require('nylas');

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

const nylas = Nylas.with(<ACCESS_TOKEN>);

Step 2: (Optional) Change the base API URL

You can choose to change the base API URL depending on your location:

Location API URL Scheduler API URL
United States (Oregon) https://api.nylas.com https://api.schedule.nylas.com
Europe (Ireland) https://ireland.api.nylas.com https://ireland.api.schedule.nylas.com

For more information, see Data residency and Migration guide for data centers.

If you're using the Node.js SDK v6.x and the Nylas API v3 Beta: The EU region is currently not available.

To change the API URL, pass the API_URL parameter to Nylas.config():

const Nylas = require('nylas');

Nylas.config({
clientId: <CLIENT_ID>,
clientSecret: <CLIENT_SECRET>,
apiServer: regionConfig[Region.Ireland].nylasAPIUrl
});

const nylas = Nylas.with(<ACCESS_TOKEN>);

If you're using the Nylas EU region: The base API URL defaults to the US region, but you can specify apiServer: regionConfig[Region.Ireland].nylasAPIUrl to use the EU region. See Data Residency for more information.

Step 3: View labels and folders

While most email providers use folders to organize email inboxes, Gmail uses labels instead. You can determine the organization method using the organizationUnit parameter, which returns either folder or label from the accounts endpoint. For more information, see the Accounts endpoint documentation.

View labels

For users who have a Gmail account, you can return the labels associated with their email account and manage them:

  1. Use if (account.organizationUnit == 'label') to ensure that you modify the account only if it uses labels.
  2. Call the nylas.labels.list({}) function to return all labels associated with the account. This returns the default labels (Inbox, Important, Trash, and Spam) along with any custom labels that user has created.
  3. (Optional) Specify attributes for the Label object. For more information about labels, see the Labels endpoint documentation.

The example below logs the displayName and id for all labels associated with a user's Gmail account.

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

View folders

For users who have an email account that uses folders to organize their inbox, you can return the folders and manage them:

  1. Use if (account.organizationUnit == 'folder') to ensure that you modify the account only if it uses folders.
  2. Call the nylas.folders.list({}) function to return all folders associated with the account. This returns the default folders (Inbox, Drafts, Trash, and Sent Items) along with any custom folders that user has created.
  3. (Optional) Specify attributes for the Folder object. For more information about folders, see the Folders endpoint documentation.

The following example logs the displayName and id for all folders associated with a user's email account.

nylas.account.get().then(account =>{
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}`);
}
});
}
});

Example: View labels and folders

The example code below determines whether the user's email account uses labels or folders to organize their inbox, and returns a list of labels or folders.

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

Step 4: Create labels and folders

The following sections describe how to create labels and folders and use them to organize email messages.

Create a label

Follow these steps to create a Gmail label and apply it to the most recent email message in a user's inbox:

  1. Define the new label name (labelName) and use labelToUpdate to specify that you want to update it.

  2. Use if (account.organizationUnit == 'label') to ensure that you modify the account only if it uses labels.

  3. Use the checkLabel() function to make sure the label doesn't already exist:

    function checkLabel (label) {
    if (label.displayName == labelName) {
    labelToUpdate = label;
    };
    }
  4. Use the createAndApplyLabel() function to create the new label, then save it to the user's Gmail account:

    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);
    }
    }
  5. Call addLabelToMostRecentMessage() to apply the new label to the most recent email in the account's inbox:

    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);
    })
    })
    }
    • nylas.messages.first() retrieves the most recent email message from the account's inbox.
    • .push(label) applies the new label to the most recent email message in the account's inbox.
    • .save() saves the changes to the user's Gmail account. It logs the subject line and all labels applied to the message.

Example: Create a label

The example below creates the "Cat Pics!" label and applies it to the most recent email message in the account's inbox.

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 => {
// account.organizationUnit will return 'label' or 'folder' depending on provider capabilities.
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 message.
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 message.
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 message and save it.
msg.labels.push(label);

msg.save().then(savedMsg => {
console.log(`Subject: ${savedMsg.subject}`);
// Gmail includes default labels, including Inbox, Important, Trash, Spam, and more.
console.log("This email contains the following labels")
console.log(savedMsg.labels);
})
})
}

Create a folder

The syntax for creating a folder is mostly the same as that for creating a label. An email message can exist in only one folder, though, while an email thread can be associated with several folders. For more information, see the Threads endpoint documentation.

Follow these steps to create a folder, and add the most recent email message in the account's inbox to it:

  1. Define the new label name (folderName) and use folderToUpdate to specify that you want to update it.

  2. Use if (account.organizationUnit == 'folder') to ensure that you modify the account only if it uses folders.

  3. Use the checkFolder() function to make sure the folder doesn't already exist:

    function checkFolder (folder) {
    if (folder.displayName == folderName) {
    folderToUpdate = folder;
    };
    }
  4. Call createAndApplyFolder() to create the new folder, then save it to the user's account:

    function createAndApplyFolder () {
    if ( !folderToUpdate ) {
    console.log(`Creating New folder: ${folderName}`)
    folderToUpdate = new Folder(nylas, {displayName: folderName});
    folderToUpdate.save().then(folder => {
    addMostRecentMessageToFolder(folder);
    });
    } else {
    console.log(`${folderName} already exists!`)
    addMostRecentMessageToFolder(folderToUpdate);
    }
    }
  5. Use addMostRecentMessageToFolder() to add the most recent email message in the account's inbox to the new folder.

    • nylas.messages.first() retrieves the most recent email message from the account's inbox and assigns msg.folder to the folder that you created. The most recent email message is then moved to the folder.
    • .save() saves the changes to the account's email provider. It logs the subject line and the folder name. For more information, see the Folders endpoint documentation.

Example: Create a folder

The example below creates the "Cat Pics!" folder and applies it to the most recent email message in the account's inbox.

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 => {
// account.organizationUnit will return 'label' or 'folder' depending on provider capabilities.
if (account.organizationUnit == 'folder') {
nylas.folders.forEach({}, checkfolder, createAndApplyFolder);
}
});
function checkfolder (folder) {
if (folder.displayName == folderName) {
folderToUpdate = folder;
};
}
function createAndApplyFolder () {
// Make sure that we aren't duplicating an existing folder name.
if ( !folderToUpdate ) {
// If the folder doesn't exist, create it and pass it to the function that moves it to the
// most recent email message.
console.log(`Creating New folder: ${folderName}`)
folderToUpdate = new Folder(nylas, {displayName: folderName});

folderToUpdate.save().then(folder => {
addMostRecentMessageToFolder(folder);
});
} else {
// If the folder already exists, pass it to the function that assigns it to the most recent
// email message.
console.log(`${folderName} already exists!`)
addMostRecentMessageToFolder(folderToUpdate);
}
}
function addMostRecentMessageToFolder (folder) {
nylas.messages.first().then(msg => {
console.log(`${folder.displayName} applied to the most recent email.`)
// Add the folder to the most recent email message and save it.
msg.folder = folder;

msg.save().then(savedMsg => {
console.log(`Subject: ${savedMsg.subject}`);
// Email providers have default folders including Inbox, Drafts, Trash, Sent Items, and
// more.
console.log("This email contains the following folders")
console.log(savedMsg.folder);
})
})
}

More resources

If you’ve made it this far, congrats! You’ve successfully learned how to manage inbox folders and labels with the Nylas Email API! 🎉

There's plenty more that you can do with Nylas. Take a look at these resources: