Tuesday, 21 July 2015

How to cleanup Gmail inbox automatically


Gmail offer almost unlimited space to store email, but in my case this space is important since i am sending so many attachment that right now my inbox is near 10gb. So with new year i decided to cleanup my inbox to have more space to store backup photos from my phone. I started to do that manually but it would take me few hours, and as developer i started googling how i can do it faster and i found good way to do that throw scripting. I found script and modified it my needs and now it works in following way, after 2 days message from inbox will be added to label "Delete me", if message is starred or added to any label then it will be ignored since this message is important for me, then messages marked with "Delete me" and older then one month will be moved to trash.
To run this script go to scripts page.  Create blank project and insert my script
var deleteLabelName = "Delete me";
var acrhiveDates = "2d";
var removeDates = "90d"
function archiveInbox() {
  // Every thread in your Inbox that is read, older than two days, and not labeled "delete me".
  var label = GetDeleteLabel();
  var threads = GmailApp.search('label:inbox older_than:'+acrhiveDates+' -label:* -is:starred');
  for (var i = 0; i < threads.length; i++) {
    threads[i].moveToArchive();
    label.addToThread(threads[i]);
    Utilities.sleep(1000);
  }
}

function GetDeleteLabel(){
  var label = GmailApp.getUserLabelByName(deleteLabelName);
  if(!label){
    label = GmailApp.createLabel(deleteLabelName)
  }
  return label;
}

function cleanupItems() {
  var batchSize = 100 // Process up to 100 threads at once
  var threads = GmailApp.search('label:"'+deleteLabelName+'" older_than:'+removeDates);
  for (j = 0; j < threads.length; j+=batchSize) {
    GmailApp.moveThreadsToTrash(threads.slice(j, j+batchSize));
  }
}
archiveInbox and cleanupItems can be runned manually or using triggers to be runned everyday. To do so click on projects triggers button in pannel

I have trigger for each hour for archiveInbox(Because it has some time limitation so to cleanup some date script should be runned multiple times) and cleanupItems daily.
Volodymyr Bilyachat Web Developer