A Google Apps Script which adds pseudo message retention-like policies against specific labels for a Gmail account.
- 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.
- 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.