Skip to content

Instantly share code, notes, and snippets.

@magnetikonline
Last active October 27, 2020 02:56
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 magnetikonline/7942dcdbc0fb3ba69cb265d152275f66 to your computer and use it in GitHub Desktop.
Save magnetikonline/7942dcdbc0fb3ba69cb265d152275f66 to your computer and use it in GitHub Desktop.
Gmail message retention/purge by label Google script.

Gmail retention/purge by label Google script

A Google Apps Script which adds pseudo message retention-like policies against specific labels for a Gmail account.

How it works

  • Apps Script function is called automatically on a regular schedule.
  • Script iterates over a set of predefined message labels.
  • For each label, perform a search for messages older than defined lifetime (e.g. label:MY_LABEL before:YYYY-MM-DD).
  • Each message found beyond the lifetime is then moved to trash.
  • Repeat for each label
  • Done.

Install

  • Go https://script.google.com/.
  • Click + New script to create new project.
  • Name project, drop contents of main.js into code area.
  • Update LABEL_LIST to an array of labels to apply retention to:
    • Labels are always lowercased in searches, without spaces or delimiters for nested labels.
    • Example:
      • My Label -> my-label.
      • Parent label/Child label -> patent-label-child-label.
    • If unsure, click on a label in the Gmail web UI and note their usage in the search bar area.
  • Set REMOVE_BEFORE_DAYS to desired number of days to keep messages against labels set above.
  • Save script, then to confirm success:
    • Run
    • Run function
    • purgeGmail
  • To view log output from function:
    • From the main Apps Script landing page...
    • My Executions
    • Find function run, right click.
    • Stackdriver logs
  • Finally to schedule automated runs:
    • Edit
    • Current project's triggers
    • Setup a "Time-driven" trigger(s) as desired.

Reference

const LABEL_LIST = [
'LABEL1',
'LABEL2'
],
REMOVE_BEFORE_DAYS = 14,
BATCH_SIZE = 100;
function purgeGmail() {
for (const labelItem of LABEL_LIST) {
// build search query and execute
console.log(`Processing label: ${labelItem}`);
const searchQuery = `label:${labelItem.toLowerCase().replace(' ','-')} older_than:${REMOVE_BEFORE_DAYS}d`;
let deleteThreadCount = 0;
while (true) {
// note: https://developers.google.com/apps-script/reference/gmail/gmail-app#searchquery-start-max
const threadList = GmailApp.search(searchQuery,0,BATCH_SIZE);
if (threadList.length == 0) {
console.log(`Trashed threads: ${deleteThreadCount}`);
break;
}
GmailApp.moveThreadsToTrash(threadList);
deleteThreadCount += threadList.length;
}
}
console.log('Done!');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment