Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading