Label Emails with Apps Script

Gmail labels help you organize your inbox into meaningful categories. With Apps Script, you can create labels, apply them to threads, and even remove them — all automatically based on sender, subject, or content.

Creating a Label

function createLabel() { var label = GmailApp.createLabel("Acme Corp / Closed Deals"); Logger.log("Label created: " + label.getName()); }

If the label already exists, Apps Script will return the existing one without throwing an error.

Getting an Existing Label

function getLabel() { var label = GmailApp.getUserLabelByName("Acme Corp / Closed Deals"); if (label) { Logger.log("Label found: " + label.getName()); } else { Logger.log("Label does not exist."); } }

Applying a Label to a Thread

function labelThread() { var threads = GmailApp.search('from:[email protected] subject:"Pro Plan"'); var label = GmailApp.getUserLabelByName("Acme Corp / Closed Deals"); if (!label) label = GmailApp.createLabel("Acme Corp / Closed Deals"); threads.forEach(function(thread) { thread.addLabel(label); Logger.log("Labelled: " + thread.getFirstMessageSubject()); }); }

Auto-Labelling Emails Based on Customer Status in Sheet

This example reads each customer from the Sales Tracker and applies a Gmail label to their email thread based on deal status:

function autoLabelByDealStatus() { var sheet = SpreadsheetApp .getActiveSpreadsheet() .getSheetByName("Sales Tracker"); var data = sheet.getRange(2, 1, sheet.getLastRow() - 1, 7).getValues(); // Columns: [Customer Name, Email, Product, Amount, Region, Sales Rep, Status] // Create or get labels var closedLabel = GmailApp.getUserLabelByName("Acme Corp / Closed") || GmailApp.createLabel("Acme Corp / Closed"); var inProgressLabel = GmailApp.getUserLabelByName("Acme Corp / In Progress") || GmailApp.createLabel("Acme Corp / In Progress"); data.forEach(function(row) { var customerEmail = row[1]; var status = row[6]; var threads = GmailApp.search('from:' + customerEmail); if (threads.length === 0) return; var label = status === "Closed" ? closedLabel : inProgressLabel; threads.forEach(function(thread) { thread.addLabel(label); }); Logger.log("Labelled " + customerEmail + " as: " + status); }); }

With the sample data:

Removing a Label from a Thread

function removeLabel() { var label = GmailApp.getUserLabelByName("Acme Corp / In Progress"); var threads = GmailApp.search('from:[email protected]'); threads.forEach(function(thread) { thread.removeLabel(label); Logger.log("Label removed from: " + thread.getFirstMessageSubject()); }); }

Listing All Threads with a Specific Label

function listClosedDealEmails() { var label = GmailApp.getUserLabelByName("Acme Corp / Closed"); if (!label) return; var threads = label.getThreads(); threads.forEach(function(thread) { Logger.log(thread.getFirstMessageSubject() + " – " + thread.getLastMessageDate()); }); }