Automating GMail

published on 2018-02-11 in computing

Automating GMail cleanup tasks turned out to be a great time saver for me. I get a lot of mail from automated processes I need to see, but don't need to keep for long. One example is monitoring alerts, another is admin/root type emails. Yet another is email notifications from servies like NextDoor, YouTube, Google Calendar, etc. I get a ton of these and I just don't need to reference them beyond a few days. Part of my weekly (sometimes daily) routine included cleaning these up. At best, a 30 second interruption. At worst, kill my email for half an hour with the dreaded "Temporary Error". So, I wrote a little script to do this for me automatically, based on labels. Now I just read & archive them (or whatever) and the script does the rest. No more cleanups and my mailbox is far more tolerable for searching.

My script is below. Follow the instructions on the GMail page here and paste the content of my script instead. Name it 'Email Cleanup' or something like that. You'll need to update the labels to match the labels you want to use to clean up.

var days31 = ["label1",
var days7 =  ["label4",

function auto_delete_mail(userLabel,days) {
  var label = GmailApp.getUserLabelByName(userLabel);
  if(label == null){
    var delayDays = days // Enter # of days before messages are moved to trash
    var maxDate = new Date();
    var threads = label.getThreads();
    for (var i = 0; i < threads.length; i++) {
      if (threads[i].getLastMessageDate()<maxDate){

days31.forEach( function(s) {
} );

days7.forEach( function(s) {
} );

I've also posted it on Github, if you see changes I should make, send me a pull request!

Tags: gmail automation