Search code examples
javascriptarraysfor-loopsearchgmail

Search gmail with an array


I am trying to use an array:

[[email protected], [email protected], [email protected]]

To search gmail to see if I have sent any messages to the above addresses in the last 7 days.

My search query is currently:

 for(var EveryWeekPerson in ArrayListedAbove){
    EveryWeekPerson.toString();

    var Emails = GmailApp.search('is:sent from:me to:' + EveryWeekPerson + '-in:chats newer_than:' + VariableStatingSevenDays);}

But this doesn't appear to be working and logging the output gives me the number 0, 1, 2 (I assume the position of the item in the array).

Ultimately I want to count how many emails were sent and if the number is zero perform some action.

I can't work out from the documentation what format the array needs to be in to to loop through it.


Solution

  • I found the answer - using the for(var EveryWeekPerson in ArrayListedAbove) enumerates while iterating (hence the 0, 1, 2 etc).

    Instead you want

    var ArrayLength = ArrayListedAbove.length()
    
    for (var i = 0; i < ArrayLength; i++) {
        var threads = GmailApp.search('is:sent from:me to:' + ArrayListedAbove[i] + ' -in:chats newer_than:' + VariableHolding7Days);
    }
    

    Essentially go through the array and take each object by its index