Gmail Script to Delete Old Emails

19 Apr

I needed a some way to automatically delete old Gmail emails.

I decided to use a script to run on a schedule to achieve this.

I first needed a way to stop any emails going into to spam. For this I used a filter:

  • Criteria – Has the words: ‘is:spam’
  • Action – Never send it to Spam

I also had issues referring to the ‘Inbox’ label in my script and so I used another filter to add the ’email’ custom label to all emails first:

  • Criteria – Greater than 0 Bytes
  • Action – Apply the label ’email’

(I also introspectively applied this to all emails in the inbox)

Then head over to https://script.google.com and create a new script, I used:

 
 
// The name of the Gmail Label that is to be autopurged?
var GMAIL_LABEL = "email";    
 
// Purge messages automatically after how many days?
var PURGE_AFTER = "120";
 
function purgeGmail() {
  
  var age = new Date();  
  age.setDate(age.getDate() - PURGE_AFTER);    
  
  var purge  = Utilities.formatDate(age, Session.getTimeZone(), "yyyy-MM-dd");
  var search = "label:" + GMAIL_LABEL + " before:" + purge;
 
  // This will create a simple Gmail search 
  // query like label:Newsletters before:10/12/2012
  
  try {
    
    // We are processing 100 messages in a batch to prevent script errors.
    // Else it may throw Exceed Maximum Execution Time exception in Apps Script
 
    var threads = GmailApp.search(search, 0, 100);
    
 
    // For large batches, create another time-based trigger that will
    // activate the auto-purge process after 'n' minutes.
 
    if (threads.length == 100) {
      ScriptApp.newTrigger("purgeGmail")
               .timeBased()
               .at(new Date((new Date()).getTime() + 1000*60*10))
               .create();
    }
 
    // An email thread may have multiple messages and the timestamp of 
    // individual messages can be different.
    
    for (var i=0; i<threads.length; i++) {
      var messages = GmailApp.getMessagesForThread(threads[i]);
      for (var j=0; j<messages.length; j++) {
        var email = messages[j];       
        if (email.getDate() < age) {
          email.moveToTrash();
        }
      }
    }
    
  // If the script fails for some reason or catches an exception, 
  // it will simply defer auto-purge until the next day.
  } catch (e) {}
  
}

I then created a trigger to run this daily.

All emails then survive in the inbox for 120 days, they are then moved to trash were they survive for a further 30 days after which time they are permanently deleted. Magic.

References: