Search code examples
google-apps-scriptgmailgmail-api

Apps Script GmailApp archiving not working


I have a function which I wish to tie to a daily time trigger in Google Apps Script. The function is supposed to take all e-mails in my Inbox marked as read that are older than 14 days and archive them. Here is the code, which I got from here

function batchArchiveA() {
  var batchSize = 100 // Process up to 100 threads at once

  var threads = GmailApp.search('label:"inbox" is:read older_than:14d -label:"Delete me"');
  for (j = 0; j < threads.length; j+=batchSize) {
    Logger.log("Thread " + j);
    GmailApp.moveThreadsToArchive(threads.slice(j, j+batchSize));
  }
}

I have run this function manually to test it out a few times. However, none of the changes seem to be reflected when I open my Inbox in Gmail. I still have 890+ e-mails in my inbox dating back to 2012 (plus more under the Promotion, Update etc. sub-labels)

Thing is, the execution output initially reported no errors, and I could see that a lot of threads were being loaded and then dealt with in the loop. However, now when I run the script, there are no threads loaded. The search simply returns an empty array and the function exits.

I'm just curious what I am doing wrong. I've looked at the Google Developers reference for the GmailApp but there's not really much I can go on so far as debugging is concerned. And presumably, since the search no longer returns anything, the previous runs actually did work... since if they did archive all the threads older than 14 then the search would indeed no longer find them.

Any ideas why I'm not seeing the e-mails gone from my inbox when I load up Gmail?


Solution

  • Okay, so it turns out it was working, but my inbox was just so clogged up that the search I believe only grabbed a maximum number of threads (which must be something like 400-500) at a time, so I didn't really notice a difference.

    I set it in a loop that keeps running as long as search returns an array bigger than 0. Meaning it will run through all threads it can (or, as at the moment, until the maximum execution time limit is hit!). I set the functions to run on a regular basis and my inbox has already shrunk to almost nothing!