Skip to content

Instantly share code, notes, and snippets.

@magnetikonline magnetikonline/README.md
Last active Jul 16, 2018

Embed
What would you like to do?
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

var LABEL_LIST = [
'LABEL1',
'LABEL2'
],
REMOVE_BEFORE_DAYS = 14,
BATCH_SIZE = 100;
function purgeGmail() {
for (var labelIndex = 0;labelIndex < LABEL_LIST.length;labelIndex++) {
// build search query and execute
console.log('Processing label: ' + LABEL_LIST[labelIndex]);
var searchQuery = 'label:' + LABEL_LIST[labelIndex].toLowerCase().replace(' ','-') + ' older_than:' + REMOVE_BEFORE_DAYS + 'd',
deleteThreadCount = 0;
while (true) {
// note: https://developers.google.com/apps-script/reference/gmail/gmail-app#searchquery-start-max
var 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
You can’t perform that action at this time.