google apps script - How to import multiple uniquely named CSV attachments from GMAIL to GOOGLESHEETS - Stack Overflow

PHOTO EMBED

Wed Mar 30 2022 22:49:45 GMT+0000 (Coordinated Universal Time)

Saved by @itsbrex #javascript

function SLSalesImportFromGmail() {
  var ss = SpreadsheetApp.getActive(); // Get the spreadsheet file once

  //gets first(latest) message with set label
  var threads = GmailApp.getUserLabelByName('South Loop').getThreads(0,1);
  if (threads && threads.length > 0) {
    var message = threads[0].getMessages()[0];

    // Get all of the attachments and loop through them.
    var attachments = message.getAttachments(); 
    for (var i = 0; i < attachments.length; i++) {
      var attachment = attachments[i];
      var title = attachment.getName();

      // Is the attachment a CSV file
      attachment.setContentTypeFromExtension();
      var table = Utilities.parseCsv(attachment.getDataAsString());
      if (attachment.getContentType() === "text/csv") {
        // Update the specified sheets
        // Clears the sheet of values & formatting and inserts the new table
        // using the Apps Script built-in CSV parser.
        switch (title) { 
          case "Sales.csv":
            ss.getSheetByName("South Loop Sales").getRange("A:M").clear();
            ss.getSheetByName("South Loop Sales").getRange(1, 1, table.length, table[0].length).setValues(table);
            break;
          case "Labor.csv":
            ss.getSheetByName("South Loop Labor").getRange("A:M").clear();
            ss.getSheetByName("South Loop Labor").getRange(1, 1, table.length, table[0].length).setValues(table);
            break;
          case "ServerPerformance.csv":
            ss.getSheetByName("South Loop Servers").getRange("A:M").clear();
            ss.getSheetByName("South Loop Servers").getRange(1, 1, table.length, table[0].length).setValues(table);            
            break;
        }
      }      
    }
    if (message.getSubject().indexOf('END OF DAY') !== -1) {
      SLlogTodaysSales();
      SLlogTodaysServers();
    }
    if (message.getSubject().indexOf('END OF WEEK') !== -1) {
      SLlogTodaysSales();
      SLlogTodaysServers();
      SLlogWeeksLabor();
    }
    // Marks the Gmail message as read, unstars it and deletes it using Gmail API (Filter sets a star)
  message.markRead();
  message.unstar();
  Gmail.Users.Messages.remove("me", message.getId()); // Added
  }
}
content_copyCOPY

https://stackoverflow.com/questions/60139596/how-to-import-multiple-uniquely-named-csv-attachments-from-gmail-to-googlesheets