4
votes

What I am trying to do, is get the contents of the CSV attachment to output onto Google Sheets. No idea if I am doing this correctly, but I found this online, ran it, and then nothing happens.

function importCSVFromGmail() {
    var threads = GmailApp.search("from:[email protected]");
    var message = threads[0].getMessages()[0];
    var attachment = message.getAttachments()[0];

    // Is the attachment a CSV file
    if (attachment.getContentType() === "text/csv") {
        var sheet = SpreadsheetApp.getActiveSheet();
        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);
    }
}
1

1 Answers

2
votes

In my environment, I confirmed that when the attached *.csv file is retrieved from the email, the mimeType is retrieved as application/vnd.ms-excel. I think that the reason of "nothing happens" is this. So how about these modifications? I think that there are several workarounds for your situation. So please think of these modification as 3 of them.

Modification points:

  • Pattern 1: Set the mimeType from filename.
  • Pattern 2: Use the mimeType as application/vnd.ms-excel
  • Pattern 3: Use the extension.

Pattern 1:

Please add the following script before if (attachment.getContentType() === "text/csv") {.

attachment.setContentTypeFromExtension();

Pattern 2:

Please modify as follows.

if (attachment.getContentType() === "text/csv") {
if (attachment.getContentType() === "application/vnd.ms-excel") {

Pattern 3:

Please modify as follows.

if (attachment.getContentType() === "text/csv") {
var fileName = attachment.getName().toUpperCase().split(".");
if (fileName.length > 1 && fileName[1] == "CSV") {

Note:

  • About pattern 1, the mimeType is set from the extension of the filename by using setContentTypeFromExtension().
  • About pattern 2, if in your environment, CSV files are retrieved as other mimeType, please modify application/vnd.ms-excel.
  • About pattern 1 and 3, if the filename of CSV file has not extension or other extension, it cannot be used under the situation.

Reference:

If these were not what you want, I'm sorry.