Search code examples
google-apps-scriptgoogle-sheetsgmailgoogle-sheets-api

using Google Script to get attachment from Gmail


So I built a spreadsheet that gets 2 reports from 2 different sources and then imports them into the sheet. One of the reports is a CSV file that is sent to my email every hour.

The script I have works....mostly. It will check my email for the thread, pull the message, and then import the attachment to the sheet. The problem is when the next email is received the next hour and the script runs again, it won't pull the most recent attachment, it will only pull the first one. I've even tried moving the message to my trash every time it runs, but it still will pull it from the trash. Here is my code.

function importReport() {

  var threads = GmailApp.search('in:inbox from:"[email protected]"');
  var message = threads[0].getMessages()[0];
  var attachment = message.getAttachments()[0];
  attachment.setContentType('text/csv');

 // Is the attachment a CSV file
 if (attachment.getContentType() === "text/csv") {

    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("RawReport");
    var csvData = Utilities.parseCsv(attachment.getDataAsString(), ",");

  // Remember to clear the content of the sheet before importing new data
   sheet.clearContents().clearFormats();
   sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);

 GmailApp.moveMessageToTrash(message);
  }


}

The goal is for it to pull the whole thread and then import the most recent attachment, any advice?


Solution

  • You should try pulling the last message from the Gmail thread instead of the first message.

    var messages = threads[0].getMessages();
    var message = messages[messages.length - 1];