Skip to content

Instantly share code, notes, and snippets.

@thibaultmol
Created August 23, 2016 05:55
Show Gist options
  • Save thibaultmol/43026b1ce15cddf438c6a0cc57acca96 to your computer and use it in GitHub Desktop.
Save thibaultmol/43026b1ce15cddf438c6a0cc57acca96 to your computer and use it in GitHub Desktop.
Google Apps Script Gmail: when sublabel and parent label, only sublabel
function startFunction() {
// If email has 1-Ingrid label and sublabel label then delete 1-Ingrid:
mainFunction("Ingrid");
mainFunction("Claire");
}
function mainFunction(name) {
var amountOfLabelsRemoved = 0;
var subLabelsWithUsername = getSubLabels(name);
for (var x = 0; x < subLabelsWithUsername.length; x++) {
var gmailApiUserLabel = GmailApp.getUserLabelByName("1-" + name);
while (gmailSearch(name,subLabelsWithUsername).length > 0) {
var results = gmailSearch(name,subLabelsWithUsername);
gmailApiUserLabel.removeFromThreads(results);
amountOfLabelsRemoved = amountOfLabelsRemoved + results.length;
}
}
Logger.log("Amount of Labels Removed for user " + name + ": " + amountOfLabelsRemoved);
}
function trialAndErrorTest() {
Logger.clear();
var subLabelsWithUsername = getSubLabels("ingrid");
gmailSearch("ingrid",subLabelsWithUsername);
}
function getSubLabels(name) {
//This function creates array with all sublabels of 1-NAME
var results = [];
var subLabelsWithUsername = [];
//Retrieve all labels and convert to text array(results)
var labels = GmailApp.getUserLabels();
for (var i = 0; i < labels.length; i++) {
results.push(labels[i].getName());
}
//Filter all labels for sublabels
for (var i = 0; i < results.length; i++) {
if(results[i].indexOf('/')>0){
var isASubLabel = results[i];
//Filter those labels for the labels of 1-NAME parent
if(isASubLabel.indexOf("1-" + name)>=0){
subLabelsWithUsername.push(isASubLabel)};
}
}
return subLabelsWithUsername;
Logger.log("function getSubLabels finished executing");
}
function gmailSearch(name,subLabelsWithUsername) {
//make search query (filter)
//var nieuwsbriefLabel = "1-" + name + "-Nieuwsbrieven";
for (var label in subLabelsWithUsername) {
if (filter == null) {
var filter = "(label:1-" + name + " AND label:" + subLabelsWithUsername[label] + ") ";
} else {
filter += "OR (label:1-" + name + " AND label:" + subLabelsWithUsername[label] + ") ";
}
}
//concatenate filter
// +" AND label:" + nieuwsbriefLabel;
var results = GmailApp.search(filter, 0, 40);
return results;
Logger.log("function gmailSearch finished executing");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment