Search code examples
google-apps-scriptgmail-apispreadsheet

How can I get the last message in the thread?


i use the following code in Google Apps Script and i wanna get last reply every mail list. This code gets every threads first mail instead of last mail.

 var myspreadsheet = SpreadsheetApp.getActiveSpreadsheet();
 var mysheet = myspreadsheet.getSheets()[0];
 var start = 0;
 var max = 399;
 var count =0;
 var row = mysheet.getLastRow()+1
 while(count < 7) 
 {

   var threads = GmailApp.getInboxThreads(start , max);
   var messages = GmailApp.getMessagesForThreads(threads); 
   var froms = [];
    messages.get
      for(var i = 0; i < threads.length; i++)
    {
       froms.push([messages[i][0].getId(),messages[i][0].getSubject(),messages[i][0].getTo(),messages[i][0].getFrom(),messages[i][0].getCc(),messages[i][0].getDate(),messages[i][0].getReplyTo()]);
    }

    mysheet.getRange(mysheet.getLastRow()+1,1,threads.length,7).setValues(froms);

    start =  start + 100;
    count++;
    }
}```

Solution

  • There is a lot going on in this script that may need to be changed.

    So the following lines are limited to getting the last message of each thread. And then pushing the details of that last message into the array from[].

      for (var i = 0; i < threads.length; i++) { // Loop through the threads
    
        var thisThread = threads[i]; // Get a speific thread
    
        var messages = thisThread.getMessages(); // Get the messages in that thread
    
        var messageCount = thisThread.getMessageCount(); // Count the number of messages in that thread
    
        var lastMessage = messages[messageCount - 1]; // Get the last message in that thread. The first message is numbered 0.
    
        froms.push([lastMessage.getId(), lastMessage.getSubject(), lastMessage.getTo(), lastMessage.getFrom()...]);
    
      }