Search code examples
gmail

Gmail scripts: Get First Message Subject of threads in a particular label Google Script


        function Label () {
 var label = GmailApp.getUserLabelByName("Tools and Credentials");
 var threads = label.getThreads(0, 30);
 for (var i = 0; i < threads.length; i++) 
 {
   var firstmessagesubject = threads[i].getFirstMessageSubject();
   Logger.log(firstmessagesubject);
   SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Pull Thread variables").getRange(2+i,1,threads.length, 1).setValue(firstmessagesubject);
 }
}

Above is the script I have written to extract the Subject of first message of threads in a particular label on GMail. The label has 11 threads. However the resulting export to spreadsheet has 21 rows with the first 11 correct entries and the last 10 being duplicates of the 11th row. Link to my result sheet : https://docs.google.com/spreadsheets/d/1eVsBsduh63kL22iXUEKsdSqzrIyQGDOHP2y5Ddtmygc/edit#gid=998793935


Solution

  • Since you are logging the values in a single cell per iteration, you only need to specify the row and column number while setting the value.

    function Label () {
      var label = GmailApp.getUserLabelByName("Tools and Credentials");
      var threads = label.getThreads(0, 30);
      var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Pull Thread variables");
      for (var i = 0; i < threads.length; i++) {
        var firstmessagesubject = threads[i].getFirstMessageSubject();
        sheet.getRange(2+i,1).setValue(firstmessagesubject);
      }
    }