Archive Old Gmail Messages Automatically

This Google Script will scan the inbox of your Gmail and archive any message that you’ve read (seen) and is older than a month. It skips messages that are either starred or marked with a particular label like toReply.

function archiveInbox() {
  var query = 'label:inbox is:read older_than:30d -in:starred -label:toreply';
  var batchSize = 100;
  
  while(GmailApp.search(query, 0, 1).length == 1) {
    GmailApp.moveThreadsToArchive(GmailApp.search(query, 0, batchSize));
  }
}

Here’s an alternate way to deal with the same issue. It checks for individual messages in a Gmail thread before moving them to the Archive.

function cleanInbox() {
  var threads = GmailApp.getInboxThreads();
  for (var i = 0; i < threads.length; i++) {
    var thread=threads[i];
    if (!thread.hasStarredMessages() && !thread.isUnread()) {
       GmailApp.moveThreadToArchive(threads[i]);
    }
  }
}