Roger Wareham
Roger Wareham

Reputation: 61

Coping CSV file from Gmail Attachment by name

I want to only copy the CSV attachment to google sheets from an email. The email has multiple attachments, in different file formats. The attachment I want to copy over is consistently the same name in csv format. I am using this code but its not pulling the attachment I want to copy to google sheet. Can someone help me with this.

function getCSV() {

 var myLabel = GmailApp.getUserLabelByName("I-Data New"); // specify label in gmail
 var threads = myLabel.getThreads(0,1);
 var msgs = GmailApp.getMessagesForThreads(threads);
 var attachments = msgs[0][0].getAttachments();

 var csv =  attachments[0].getDataAsString();
 var data = Utilities.parseCsv(csv);

var a = data.length ;
var b = data[0].length; 

var ss = SpreadsheetApp.getActiveSpreadsheet();
 var sheet = SpreadsheetApp.openById('12ApSC0WVn1sZxb9VF6_CZR9L5xuGY5WHMLyyGMc').getSheetByName('IData');
  sheet.getRange('A2:AM6026').clearContent();
  var range = sheet.getRange(2,1, data.length,data[0].length);
range.setValues(data);

}

Upvotes: 0

Views: 193

Answers (1)

RemcoE33
RemcoE33

Reputation: 1610

Loop over the attachments and get the filename. Quick edit to your existing code:

function getCSV() {

  var myLabel = GmailApp.getUserLabelByName("I-Data New"); // specify label in gmail
  var threads = myLabel.getThreads(0, 1);
  var msgs = GmailApp.getMessagesForThreads(threads);
  var attachments = msgs[0][0].getAttachments();

  attachments.forEach(att => {
    const name = att.getName()
    if (name == "myFileName.csv") {
      var data = Utilities.parseCsv(att.getDataAsString());

      var sheet = SpreadsheetApp.openById('12ApSC0WVn1sZxb9VF6_CZR9L5xuGY5WHMLyyGMc').getSheetByName('IData');
      sheet.getRange('A2:AM6026').clearContent();
      var range = sheet.getRange(2, 1, data.length, data[0].length);
      range.setValues(data);
    }
  })
}

Upvotes: 1

Related Questions