Scripting Gmail

In an attempt to get on top of my email this year, I thought about writing an app to auto cleanup my inbox based on various rules. I love the idea of inbox zero, but would rather a lot of the heavy lifting was done for me - hitting archive is just too much work.

It turns out that Google provide a really easy way to script various google services, including gmail, through "scripts" within Google Drive. It's really straightforward: you can just write scripts in JavaScript with various google libraries to talk to each service, and since it's all within your google account you don't have to deal with authentication etc. You can easily set scripts up to auto-run every hour, day, etc too.

Since Ben Werdmuller asked for someone to write an app with almost the same functionality I figured I should write it up.

  1. Go to Google Drive, and do Create > More > Script

  2. You can then script away to your hearts content. Here's the documentation for the GmailApp library. Here's my example where I automatically archive anything that's over seven days old that I haven't starred.

     function archiveOld() {
       var q = 'in:inbox -is:starred older_than:7d';
       var threads = GmailApp.search(q);
    
       for (var thread in threads) {
         GmailApp.moveThreadToArchive(threads[thread]);
       }
     }
    
     archiveOld();
    
  3. You can set up triggers to run your script daily/hourly etc with Resources > Current script triggers.

  4. For more documentation on possible search queries like in my example above, the very extensive search parameters docs are available here.