Thursday 28 March 2019

Create Gmail label if not exist

The following Google Apps Script code is designed to search through the labels in your Gmail inbox looking for a specific one, then create it if not found. I developed the function as part of the Bulk email saving tool for Gmail that I will be detailing later in the blog, where completed emails that have been saved to Google drive would then be moved into this label as a way of tracking progress.

The tool takes an input parameter of newLabel which would simply be the name of the label to search for and then create. We start by getting the existing Gmail labels ('getUserLabels') from which we can loop through each one and get their name, for pushing into an array:
for (var i=0; i<labelsLength; i++) {
    var labelName = labels[i].getName();
    labelsArray.push(labelName);
}
Next we can loop through the array looking for a match, for which we also include a 'break' so that the loop exits when it finds one - this helps to save time by avoiding continuing to look through the rest of the labels unnecessarily:
if (labelsArray[j] == newLabel) {
      var labelExists = true;
      break;
}
Depending upon the outcome of the if statement we set a variable labelExists to either true or false so that it can be evaluated in the next bit of code. If the variable is false (the label does not already exist) then we can proceed to create it:
var completedLabel = GmailApp.createLabel(newLabel);
In either scenario the last thing we do is get the new/existing label so it can be accessed by a parent function:
var labelCompleted = GmailApp.getUserLabelByName(newLabel);
return labelCompleted;

Create Gmail label if not exist.gs (please use 'Overview' > 'Make a copy' for your own version).

5 comments:

  1. Simpler way to do this:

    try {
    GmailApp.createLabel(newLabel);
    } finally {
    myLabel = GmailApp.getUserLabelByName(newLabel);
    }

    ReplyDelete
  2. Hi Phil!

    It is the third time you come out with a solution for my coding problems.

    Thanks a lot for sharing. Appreciate it!

    ReplyDelete
    Replies
    1. Hello!

      That's excellent! Thanks for letting me know!

      Kind regards
      Phil

      Delete