Home > Net >  Get attachment from most recent message in a thread
Get attachment from most recent message in a thread

Time:10-11

I am trying to get google apps script to retrieve the most recent messages received in Gmail search, and then copy the contents of the csv attachment to a Google spreadsheet.

Most works fine, however my script keeps finding the oldest message received.

Code Below

function update12MonthTabv4() {
  //FIND EMAIL
  var searchTerm = "label:new_12monthOtb"
  var threads = GmailApp.search(searchTerm)
  var message = threads[0].getMessages()[0];
  Logger.log("email found!");

  //GRAB ATTACHMENT FROM FOUND EMAIL 
  var attachment = message.getAttachments()[0];
  Logger.log(attachment.getContentType());

  //REMOVE LABEL
  var label = GmailApp.getUserLabelByName("new_12monthOtb");
  var threads = label.getThreads();
  for (var i = 0; i < threads.length; i  ) {
  threads[i].removeLabel(label);}
  Logger.log("Label Remvoed");

  //FIND SPREADHSEET
  var ss = SpreadsheetApp.openById ("16S3INZFMQDY3yguNZ2QHvzMQXI1Kf97DkSvcYyZeiHM");
  Logger.log("SS Opened");

  //FIND SHEET INSIDE SPREADHSEET
  var sheetName = ss.getSheetByName("Paste Duetto Report - 12 Month OTB");
  Logger.log("Tab Found");

  //PARSE CSV DATA
  var csvData = Utilities.parseCsv(attachment.getDataAsString('ISO-8859-1'), ",");
  Logger.log("CSV data loaded");
    
  //INSERT DATA AKA .getRange(row, column, lastrow based on CSV data);
  sheetName.getRange(2, 2, csvData.length,csvData[0].length).setValues(csvData);
  Logger.log("Data pasted");

  //HIDE SHEET
 // sheetName.hideSheet();
  Logger.log("sheet hidden");
  Logger.log("Script Complete");
}

CodePudding user response:

Your problem is that you want to select the latest message in a thread, but your script is selecting the oldest message.

Cause

  • var message = threads[0].getMessages()[0];
  • messages in a thread are zero-based, and are counted from the oldest to the newest.
  • by choosing getMessages()[0] you are specifically selecting the oldest message.

Correction

  // select all the messages for the thread
  var messages = threads[0].getMessages()
  // count the messages in the thread
  var messageCount = messages.length
  Logger.log("number of messages" messageCount)
  // get the latest message (zero-based: so count minus 1) 
  var message = messages[messageCount-1]
  Logger.log("subject" message1.getSubject() ", from:" message1.getFrom() ", and date:" message1.getDate())
  Logger.log("email found!")
  • Related