Search code examples
google-apps-scriptgoogle-sheetsgmail

The Following Apps Script code gets the oldest email the thread (from gmail), how can I make it get the latest one?


The following code is the one I currently use to import csv files into a google sheet, everything is working perfectly, except the code always fetches the oldest email in the thread and I want it to always select the newest one.

function importCSVFromGmail() {

  var threads = GmailApp.search('subject:(Daily Scheduled Report Recruiting Metrics) AND newer_than:3h'); // enter search criteria here
  var message = threads[0].getMessages()[0];
  var attachment = message.getAttachments()[0];


  var sheet = SpreadsheetApp.openById('1mflZmtgChZOFGVdlnyNrlDmVOxKEw6Hk0RJzilTvnMo').getSheetByName('Sheet1');
  var csvData = Utilities.parseCsv(attachment.getDataAsString(), ",");

   sheet.clearContents().clearFormats(); // clears target sheet
   sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData); // adds data to the sheet
}

Solution

  • Try to replace var message = threads[0].getMessages()[0]; by

    var message = threads[0].getMessages()[Number(threads[0].getMessageCount()-1)];