Only show these results:

Manage inbox labels and folders with the Nylas Node.js SDK

The Nylas Node.js SDK and the Email API help you manage the following:

  • Email labels for Gmail accounts
  • Inbox folders for various providers, such as Microsoft Outlook, Exchange, and Office365

What you'll learn

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

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

Prerequisites

Prerequisites include how to install the Nylas Node.js SDK and set up your environment. Before you start this tutorial, make sure that you do the following:

Step 1: Initialize the Nylas object

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 Nylas APIs. Before making any request, 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 (<CLIENT_ID>) and client secret (<CLIENT_SECRET>).

  2. Call the with function and pass your access token (<ACCESS_TOKEN>).

const Nylas = require('nylas');

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

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

Step 2: View labels and folders for an email account

Gmail uses labels to organize email inboxes, while most other email providers use folders. Nylas detects the organization method by using the organizationUnit, which returns either label or folder.

View labels

  1. Add if (account.organizationUnit == 'label') to see if the account uses labels.

    Learn more about Accounts.

  2. Call the nylas.labels.list({}) function to return all the labels.

    The nylas.labels.list({}) function returns default labels, such as Inbox, Important, Trash, and Spam, and any custom labels that the user created. Learn more about Labels.

  3. Optionally, specify attributes for the label object.

The following example logs the displayName and id for all labels that 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}`);
}
});
}
});

View folders

  1. Check the account endpoint and add if (account.organizationUnit == 'folder') to see if the account uses folders.

    Learn more about Accounts.

  2. Call the nylas.folders.list({}) function to return all the folders.

    Learn more about Folders.

  3. Optionally, specify attributes for the folder object.

The following example logs the displayName and id for all folders that an email account contains.

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 for an email account

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 3: Create labels and folders

You can create a Gmail label and apply it to emails or create a folder to organize emails.

Create a new label and apply it to an email

Create a Gmail label and apply it to the most recent email.

  1. Define the new label name (labelName) and labelToUpdate.

    const labelName = 'Cat Pics!';
    let labelToUpdate;
  2. Check the account endpoint and add if (account.organizationUnit == 'label') to see if the account uses labels.

    nylas.account.get().then(account => {
    if (account.organizationUnit == 'label') {
    nylas.labels.forEach({}, checkLabel, createAndApplyLabel);
    }
    });
  3. Call the checkLabel (label) function to check if the label already exists.

    function checkLabel (label) {
    if (label.displayName == labelName) {
    labelToUpdate = label;
    };
    }
  4. Call the createAndApplyLabel () function to create the new label.

    The .save() function saves the changes to Gmail. Learn more about Labels.

    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 the addLabelToMostRecentMessage() function to apply the new label to the most recent email.

    • The nylas.messages.first() function retrieves the most recent email from the inbox.
    • The .push(label) function applies the new label to the most recent email.
    • The .save() function saves the changes to Gmail. It logs the subject line and all labels that have been applied to the message.

    Learn more about Messages.

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

Example: Create a Gmail label and apply it to an 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 => {
// 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
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 default labels, including Inbox, Important, Trash, Spam, and more
console.log("This email contains the following labels")
console.log(savedMsg.labels);
})
})
}

Create a folder to organize emails

Most email providers, including Microsoft Outlook, Exchange, Office365, and Yahoo, use folders to organize emails. In this tutorial, you'll create a folder and add the most recent email to the folder.

The syntax is mostly the same as creating a label. However, an email message can only exist within one folder, while an email thread can be associated with several folders. Learn more about Threads.

  1. Define the new folder name (folderName) and folderToUpdate.

    const folderName = 'Cat Pics!';
    let folderToUpdate;
  2. Check the account endpoint and add if (account.organizationUnit == 'folder') to see if the account uses folders.

    nylas.account.get().then(account => {
    if (account.organizationUnit == 'folder') {
    nylas.folders.forEach({}, checkfolder, createAndApplyfolder);
    }
    });
  3. Call the checkFolder (folder) function to check if the folder already exists.

    function checkFolder (folder) {
    if (folder.displayName == folderName) {
    folderToUpdate = folder;
    };
    }
  4. Call the createAndApplyFolder () function to create the new folder.

    The .save() function saves the changes to the user's inbox. Learn more about Folders.

    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. Call the addMostRecentMessageToFolder() function to add the most recent email to the folder.

    • The nylas.messages.first() function retrieves the most recent email from the inbox and assigns msg.folder to the folder that you created. The most recent email is moved to the folder.
    • The .save() function saves the changes to the user's inbox. It logs the subject line and the folder.

    Learn more about Messages.

Example: Create a folder to organize emails

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
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
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 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 the following resources: