Skip to content

Instantly share code, notes, and snippets.

@reconbot
Created January 17, 2024 21:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reconbot/7514dcc7798f260edc172fd451d3da03 to your computer and use it in GitHub Desktop.
Save reconbot/7514dcc7798f260edc172fd451d3da03 to your computer and use it in GitHub Desktop.
// label any email with archive-after/2-hours or archive-after/1-day (any number of days or hours) and it does!
// you can optionaly nest the labels eg `archive-after` and make `2-hours` inside the archive after - the script doesn't seem to care!
// Install steps
// create a new project here https://script.google.com/
// create a new file with this contents
// then create a trigger to run it every 10 minutes
// enjoy!
const LABEL_REGEX = /archive-after\/(\d+)-(day|hour)s?/
const HOUR = 1000 * 60 * 60
function archiveAfterLabels() {
const labels = GmailApp.getUserLabels()
const rules = []
for (const label of labels) {
const labelName = label.getName()
const match = labelName.match(LABEL_REGEX)
if (!match) {
continue
}
const [, duration, period] = match
let multiplier = 0
switch (period) {
case 'day': multiplier = 24; break;
case 'hour': multiplier = 1; break;
default: continue;
}
rules.push([label, Number(duration) * HOUR * multiplier])
}
console.log('detected rules', rules.map(([label, timeout]) => [label.getName(), timeout]))
for (const [label, timeout] of rules) {
const labelName = label.getName()
const search = `label:${labelName} in:inbox `
const threads = GmailApp.search(search, 0, 100)
for (const thread of threads) {
const threadTime = thread.getLastMessageDate().getTime()
if (threadTime < (Date.now() - timeout)) {
console.log('archiving and removing label', thread.getFirstMessageSubject(), labelName)
thread.moveToArchive()
thread.removeLabel(label)
} else {
console.log('skipping', thread.getFirstMessageSubject(), labelName, `Remaining time ${Math.floor((threadTime - (Date.now() - timeout)) / 1000)} seconds`)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment