Reputation: 21725
With Google Apps Script, is it possible to remove empty (unused) Gmail labels?
Upvotes: 0
Views: 1948
Reputation: 1984
Based on the answers above, here is a Google Apps Script to delete empty labels (with nested labels check). The Javascript is rough, but it works! The 'testing' variable determines if it just logs or actually deletes the labels.
You can debug, run Google Apps Scripts at https://script.google.com
//
// Set to 'false' if you want to actually delete labels
// otherwise it will log them but not delete them.
//
var testing = true;
//
// Deletes labels with no email threads
//
function deleteEmptyLabels() {
Logger.log("Starting label cleanup");
var allLabels = GmailApp.getUserLabels();
var emptyLabels = allLabels.filter(function(label){ return isTreeEmpty(label, allLabels); } );
for (var i = 0; i < emptyLabels.length; i++){
Logger.log('Deleting empty label ' + emptyLabels[i].getName());
if (!testing){
emptyLabels[i].deleteLabel();
}
}
Logger.log("Finished label cleanup");
}
//
// Finds labels below a parent
//
function getNestedLabels(parent, allLabels) {
var name = parent.getName() + '/';
return allLabels.filter(function(label) {
return label.getName().slice(0, name.length) == name;
});
}
//
// Tests a single label for 'emptiness'
//
function isLabelEmpty(label){
return label.getThreads(0, 1) == 0;
}
//
// Tests a label, and nested labels for 'emptiness'
//
function isTreeEmpty(label, allLabels){
if (!isLabelEmpty(label))
return false;
var nested = getNestedLabels(label, allLabels);
for(var j = 0; j < nested.length; j++){
if (!isTreeEmpty(nested[j], allLabels))
return false;
}
return true;
}
Upvotes: 4
Reputation: 11
GmailApp.getUserLabels(), getThreads() and deleteLabel() is the way to go, but take care not to delete empty labels if one of its sub-labels is not!
Upvotes: 1
Reputation: 7367
Certainly, first use GmailApp.getUserLabels() to retrieve all the labels, then loop over them and use getThreads() to determine if a given label is empty, and finally use deleteLabel() to remove empty ones.
See:
https://developers.google.com/apps-script/reference/gmail/gmail-app
https://developers.google.com/apps-script/reference/gmail/gmail-label
Upvotes: 1