TypeError: Can not call method "getThreads" of null

1

I need to implement the following code for the massive deletion of emails in a Gmail account (the code is not mine), but I can not get it to work.

The code I use is the following:

function cleanUp() {
    var delayDays = 365 // Enter # of days before messages are moved to trash

    var maxDate = new Date();
    maxDate.setDate(maxDate.getDate()-delayDays);

    var label = GmailApp.getUserLabelByName("delete me");
    var threads = label.getThreads();
    for (var i = 0; i < threads.length; i++) {
        if (threads[i].getLastMessageDate()<maxDate)
        {
            threads[i].moveToTrash();
        }
    }
}

function archiveInbox() {
    // Every thread in your Inbox that is read, older than two days, and not labeled "delete me".
    var threads = GmailApp.search('label:inbox is:read older_than:2d -label:"delete me"');
    for (var i = 0; i < threads.length; i++) {
        threads[i].moveToArchive();
    }
}

However, I'm throwing an error on line 8 with the following message:

  

TypeError: Can not call method "getThreads" of null

I hope someone can help me, thanks.

    
asked by Valdemar Allan Poe 11.06.2016 в 19:03
source

1 answer

1

A similar thing happened to me a while ago.

You have the problem in

var label = GmailApp.getUserLabelByName("delete me");

What happens if you do not have messages with that label? The logical thing to do would be to think that the function returns a list of 0 elements, but what it does is return a null.

The solution is to look first if you have returned something or not:

function cleanUp() 
{
    var delayDays = 365 // Enter # of days before messages are moved to trash

    var maxDate = new Date();
    maxDate.setDate(maxDate.getDate()-delayDays);

    var label = GmailApp.getUserLabelByName("delete me");
    if(label != null)
    {
        var threads = label.getThreads();
        for (var i = 0; i < threads.length; i++) 
        {
            if (threads[i].getLastMessageDate()<maxDate)
            {
                threads[i].moveToTrash();
            }
        }
    }
    else
    {
        Logger.log("No hay mensajes a eliminar");
    }
}

I have not tried the code but I'm convinced it works.

    
answered by 12.06.2016 в 00:05