Google-sheets – Only the first thread is displayed in the Apps Scripts program, but I need all the threads

google sheetsgoogle-apps-script

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);
    }
   }

Best Answer

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
  }
}