Automated Gmail Cleanup

Perhaps you have noticed that you are unable to make a filter with an age interval instead of a fixed date. Perhaps you have noticed that Gmail likes to keep everything, even things that become meaningless after some time. Maybe you get an (opt-in) advertisement from a retailer with a coupon code for the next week. Do you really need to keep that email forever? Logic tells me “no”.  What about that online order for pizza or burritos from 5 years ago, is that a useful thing to keep? Again, logic says “no”.

Even large corporations understand the value of having a retention policy for emails. (Although, if your company uses GSuite, check the company policy before you start defining your own rules)

Inbox Zero

There is also a great benefit to archiving messages from your inbox (especially when using the Gmail category view). So this automated cleanup provides a facility to automatically archive emails as well.

Pre-Requisites

In order for this script to work as-is you will need the following labels in your Gmail account available to tag emails. It isn’t neccessary to add them all, these are the rules mapped in the source code as it is here.

  • retention
    • keep1day
    • keep1month
    • keep1year
    • keep3days
    • keep3months
    • keep3years
    • keep7days
    • keep7months
    • keep7years
    • keep1year

It is beneficial to have these underneath the parent label. Since these are just for your retention policy and not for categorizing, you could also hide the parent label from your sidebar as well.

Note the sublabel keepunread. This is an override label that will stop cleanup processing on that message.

Script Setup

In the function dropdown select “Install” and then click the “play” button (looks like a triangle). The system will ask you to confirm the permissions needed by the script. Accept these permissions and then click the play button one more time. The script will schedule itself to run each day at midnight.

Script Removal

When you no longer want the script to purge your expired emails, then log back into Google Apps Script. Edit the project. Select the “Uninstall” function from the dropdown, and click the “play” button. This will remove any scheduled executions of the script.

Keep Unread Email

If you want to keep unread messages even if they match an existing cleanup rule, then add the additional keepunread label to the email. Without that label then messages will be autoarchived and cleaned.

Open-Source

Want to tweak the code of this script to do things differently? Need to submit a bug report? The source is open and can be seen at this link.