Using google scripts to rename labels in gmail

I like Gmail. While I recognize it can get lumped into a “social media” bucket and I’m not the biggest fan of pixel tracking, targeted advertisements, and other online marketing shenanigans, I find it to be a nice productivity tool. It also has a nice suite of hotkeys and vim-like shortcuts that allow me to sort and label emails with ease. This is what I really love.

At this point in my life, I am a zero-inbox guy. I apply the 5S mantra to my inbox, “Everything has a place, and everything should go in its place”. So, I have labels for everything. Over the years, I have used different naming conventions and nesting for my labels, and I have finally decided to go with a regular old lower case. I think this will help me continue to use keyboard shortcuts and remain productive. So, I wrote a quick google script to help me migrate from kebab case to space-separated lower case.

I’m not going to go into detail about how to use google scripts here, but you should know I have been using them more and more for productivity tasks. One of my more recent projects allows me to use a google sheet to develop a yearly roadmap with timeline and dates calculations. I then pump those calculated dates out to my team’s shared google calendar events and jira tickets. It has been a massive time saver.

Anyways, here’s the script to rename labels:

// Author: Brandon C Sammons
// https://github.com/bsamm
// 10/27/2020
// Goal: Write a simple script to rename and normalize labels in gmail.
// API Reference: https://developers.google.com/apps-script/reference/gmail/gmail-app
function main() {
var labels = GmailApp.getUserLabels().slice(0, 50); // use .slice(0, 1) method to get first 1 label, if you just want to test
var processedLabels = [];
var unprocessableLabels = [];
for (var i = 0; i < labels.length; i++) {
var oldLabel = GmailApp.getUserLabelByName(labels[i].getName());
var threads = oldLabel.getThreads();
if (threads.length > 99) {
unprocessableLabels.push(oldLabel.getName());
} else {
var newLabel = oldLabel.getName().replace(/-/g, ' ').toLowerCase(); // adjust this line to change the casing for labels, I am going with simple lower case.
if (oldLabel != newLabel) {
GmailApp.deleteLabel(oldLabel);
GmailApp.createLabel(newLabel).addToThreads(threads);
processedLabels.push(newLabel);
Logger.log("Successfully processed this label: " + newLabel);
}
}
}
Logger.log("Successfully processed these labels: " + processedLabels);
Logger.log("Can\'t process these labels: " + unprocessableLabels);
}

Note: google scripts timeout after 5 minutes, so if you have a lot of labels you may run into this error.

brandon

About Brandon C Sammons

Brandon is a versatile and passionate engineer that uses design thinking and web technologies for creative problem-solving. He is currently working as the Director of Software at SXSW and teaching Web Design at FIDM.