0

My issue is that the first thread in my inbox is being displayed 45 times which is the number of messages in my inbox. What I need is the for loop to go through all the threads and gather all the information in the threads into a 2D array.

I know the issue is most likely with var message = threads[i].getMessages()[0] but I'm not sure how to solve the problem.

This my code:

function TheaThreads(){
    var SS =SpreadsheetApp.getActiveSpreadsheet();
    var ThreadSheet = SS.getSheetByName("Threads");
    var threads = GmailApp.getInboxThreads();
  for (var i=0; i < threads.length; i++) {
    var message = threads[i].getMessages()[0],
    label = threads[i].getLabels(),
    //subject = message.getSubject(),
    //content = message.getPlainBody(),
    ident = message.getId(),
    emailfrom = message.getFrom();

  if(label==null|| label== undefined|| label.length==0){
    label="No Label";
  }

  var threadArray = new Array();
  for(i=0; i<threads.length; i++){
    threadArray[i] = new Array();
    threadArray[i][0]= ident;
    threadArray[i][1]= label;
    threadArray[i][2]= emailfrom;

    Logger.log(threadArray);
    }
   }
0

You need to add a loop to iterate over all the messages of each thread.

for (var i=0; i < threads.length; i++) {
  for (var j = 0; j < threads[i].getMessages().length; j++){
    var message = threads[i].getMessages()[j];
    // add here what you need to do with each message
  }
}
2
  • I still have the same issue. What i realized is the i in the for loop only goes to the first element which is the first thread and stops. Im not sure whether I'm using an incorrect method to get the threads or whether there is another issue in my code. – Andray G Apr 2 at 21:59
  • See my answer to your follow-up question: -> stackoverflow.com/q/66937421/1595451 – Rubén Apr 4 at 3:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.