Skip to content

Instantly share code, notes, and snippets.

@diogotito
Created July 10, 2024 18:40
Show Gist options
  • Save diogotito/56d54db15f224d749b388ad8493c3d9d to your computer and use it in GitHub Desktop.
Save diogotito/56d54db15f224d749b388ad8493c3d9d to your computer and use it in GitHub Desktop.
Adds the label "newsletters" to any Gmail thread that has any label under it (like "newsletters/blogs")
function fixNewsletterLabels() {
const LABEL_NAME = PropertiesService.getScriptProperties().getProperty('root label') ?? "newsletters"
let rootLabel = GmailApp.getUserLabelByName(LABEL_NAME)
// Get the "newsletters" label and all labels under it
let newsLabelsNames = GmailApp.getUserLabels()
.map(label => label.getName())
.filter(labelName => labelName.startsWith(LABEL_NAME + "/"));
let query = "-label:newsletters ";
query += newsLabelsNames
.map(name => `label:${name.replaceAll(/[/ ]/g, '-').toLowerCase()}`)
.join(" OR ");
Logger.log(query);
let threads = GmailApp.search(query);
Logger.log(`found ${threads.length} emails with labels under #[${LABEL_NAME}/] without #[${LABEL_NAME}]`);
for (let thread of threads) {
Logger.log(`Adding #[${LABEL_NAME}] to ${thread.getLastMessageDate().toISOString()} "${thread.getFirstMessageSubject()}"`);
thread.addLabel(rootLabel)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment