Skip to content

Manage folders and labels with Node.js

This page explains how to use the Nylas Node.js SDK and Email API to organize a user’s inbox using folders and labels.

Before you begin

Before you start, you must have done the following tasks:

List folders and labels

Depending on the user’s email provider, there are two possible ways their inbox might be organized: using either folders or labels. Gmail uses labels, and all other providers use folders. Nylas consolidates both folders and labels under the Folders endpoint.

The following example lists all folders and labels from a user’s inbox.

async function fetchFolders() {
try {
const folders = await nylas.folders.list({
identifier: "<NYLAS_GRANT_ID>",
});
console.log("folders:", folders);
} catch (error) {
console.error("Error fetching folders:", error);
}
}
fetchFolders();

Create folders and labels

The following example creates a folder called “Cat Pics!” and applies it to the most recent message in the user’s inbox.

import "dotenv/config";
import Nylas from "nylas";
const NylasConfig = {
apiKey: "<NYLAS_API_KEY>",
apiUri: "<NYLAS_API_URI>",
};
const nylas = new Nylas(NylasConfig);
const identifier = "<NYLAS_GRANT_ID>";
const messageId = "<MESSAGE_ID>";
let folderId = "";
const createFolder = async () => {
try {
const folder = await nylas.folders.create({
identifier,
requestBody: {
name: "Cat Pics!",
},
});
console.log("Folder created:", folder);
folderId = folder.data.id;
} catch (error) {
console.error("Error creating folder:", error);
}
};
const updateMessageFolder = async () => {
try {
const updatedMessage = await nylas.messages.update({
identifier,
messageId,
requestBody: {
folders: [folderId],
},
});
console.log("Message updated:", updatedMessage);
} catch (error) {
console.error("Error updating message folder:", error);
}
};
await createFolder();
await updateMessageFolder();