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++) {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:
var labelName = labels[i].getName();
labelsArray.push(labelName);
}
if (labelsArray[j] == newLabel) {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 labelExists = true;
break;
}
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).
Simpler way to do this:
ReplyDeletetry {
GmailApp.createLabel(newLabel);
} finally {
myLabel = GmailApp.getUserLabelByName(newLabel);
}
Hi John
DeleteThanks for an alternative.
Kind regards
Phil
Nice!
DeleteHi Phil!
ReplyDeleteIt is the third time you come out with a solution for my coding problems.
Thanks a lot for sharing. Appreciate it!
Hello!
DeleteThat's excellent! Thanks for letting me know!
Kind regards
Phil