google-apps-scriptgmail

Trying to clean old messages


I have 58,000 old emails in my Gmail account, and I think that I need to get rid of them. GAS is my best bet. I want to get all the emails that: 1) Are more than X days old, AND 2) Have no user labels, and move them all to trash. I know that Gmail will "choke" on thousands of messages, so I'd like to chew through the selected emails in batches of 100. I figured that I wouldn't need to put logic in my script to create each batch, just return 100 through a limited query and run the script more frequently.

So, here's what I put together:

function cleanGmail() {
var threads = GmailApp.search('older_than:7d has:nouserlabels', 10, 10);
GmailApp.moveThreadToTrash(threads);

Except that I'm getting an error (and obviously, no messages are moved). Here's what I get when I run my script:

Notice
Execution started

Error
Exception: The parameters (number[]) don't match the method signature for GmailApp.moveThreadToTrash. @ Code.gs4

I have to confess that I really don't know what GAS is trying to tell me. I went back in to the GAS documentation, but it didn't help me too much. Does anyone have any ideas about what's going on? Better yet, how can I fix this?


Solution

  • It might be possible that the error occurs because there is typo. To passing threads as parameter change

    From

    GmailApp.moveThreadToTrash(threads);
    

    To

    GmailApp.moveThreadsToTrash(threads);
    //                 ^   Inserted s character. Don't include this line.
    

    Still, there are chances to get an error when search doesn't return the expected type, in this case a Array of GmailApp.GmailThread.

    The simplest way to "fix" the code is to avoid getting the error when there are no threads to trash is by adding an if statement as follows:

    function cleanGmail() {
    var threads = GmailApp.search('older_than:7d has:nouserlabels', 10, 10);
    if(threads.length >  0) GmailApp.moveThreadsToTrash(threads);