google-apps-scriptcsv-import

Need help in importing a CSV file data from Gmail attachment to an existing Google sheet


I am new in this group, and I don't have any experience in apps scripts.

I am here asking for some help to develop a script which can import data from CSV file in Gmail attachment. I have to develop a report on daily basis using this imported data from the CSV file. Following are the scenarios. The CSV files are automatically generated and received to my Gmail inbox on a scheduled time. Those emails can be identified by "sender email id" and "subject". Only one csv file attachment will be there in each mail. The CSV attachments are having same file name but are sent as separate email with separate subjects. I want to import these csv attachments into an existing Gsheet. Based on mail subject, each csv data should replace the entire contents of the existing sheets of this Gsheet.

I searched web and even in this group for the script but was not successful. I am posting a script which I got from the web. But it's not working.

function ExtractCSVFromGmailAndImport() {
 var label = "Report Data"; // Replace with your desired label
 var subjects = ["Data 1", "Data 2", "Data 3"]; // Replace with your desired subjects
 var spreadsheetId = "12345678900987654311"; // Replace with your Google Sheets file ID

 // Import CSV data into each sheet
for (var i = 0; i < subjects.length; i++) {
 var subject = subjects[i];
 var sheetName = subject;
 var sheet = SpreadsheetApp.openById(spreadsheetId).getSheetByName(sheetName);

 // Clear existing data in the sheet
 sheet.clear();

 // Get the Gmail label
 var threads = GmailApp.search('label:' + label + ' subject:' + subject);

 // Retrieve the CSV attachment from the email
 for (var j = 0; j < threads.length; j++) {
  var thread = threads[j];
  var messages = thread.getMessages();

  for (var k = 0; k < messages.length; k++) {
    var message = messages[k];
    var attachments = message.getAttachmentsByType('application/csv');

    if (attachments.length > 0) {
      var attachment = attachments[0];
      var csvData = Utilities.newBlob(attachment.getDataAsString()).getDataAsString();
      var csv = Utilities.parseCsv(csvData);
      sheet.getRange(sheet.getLastRow() + 1, 1, csv.length, csv[0].length).setValues(csv);
     }
    }
   }
  }
 }

While running this script I am getting error as follows

Error
TypeError: message.getAttachmentsByType is not a function ExtractCSVFromGmailAndImport @ Code.gs:25

Kindly help me in this script.


Solution

  • The error occurs since getAttachmentsByType() is not a method in Class GmailApp.

    I have tweaked your existing script from using getAttachmentsByType() to getAttachments() to obtain your desired outcome.

    The script works as follows:

    1. Clear the existing content of the sheets with the same subject name
    2. Search emails with the desired subject
    3. If emails exist,obtain the message along with attachments
    4. If an attachment is text/csv,paste the content to the sheet with its same subject name

    Modified script:

    function ExtractCSVFromGmailAndImport() {
      var subjects = ["Data 1", "Data 2", "Data 3"]; // Replace with your desired subjects
      var spreadsheetId = "1234545"; // Replace with your Google Sheets file ID
    
      // Import CSV data into each sheet
      for (var i = 0; i < subjects.length; i++) {
        var subject = subjects[i];
        var sheetName = subject;
        var sheet = SpreadsheetApp.openById(spreadsheetId).getSheetByName(sheetName);
    
        // Clear existing data in the sheet
        sheet.clear();
    
        // Get the Gmail label
        var threads = GmailApp.search('subject:' + subject);
    
        // Retrieve the CSV attachment from the email
        for (var j = 0; j < threads.length; j++) {
          var thread = threads[j];
          var messages = thread.getMessages();
    
          for (var k = 0; k < messages.length; k++) {
            var message = messages[k];
            var attachments = message.getAttachments()[k];
            if (attachments.getContentType() === 'text/csv') {
              var csvData = Utilities.newBlob(attachments.getDataAsString()).getDataAsString();
              var csv = Utilities.parseCsv(csvData);
              sheet.getRange(sheet.getLastRow() + 1, 1, csv.length, csv[0].length).setValues(csv);
            } else {
              Logger.log('No CSV file found.');
            }
          }
        }
      }
    }
    

    Sample CSV file from email:

    enter image description here

    Data 1:

    enter image description here

    Data 2:

    enter image description here

    Data 3:

    enter image description here

    Output:

    enter image description here

    References:

    https://developers.google.com/apps-script/reference/gmail/gmail-app

    https://developers.google.com/apps-script/reference/gmail/gmail-message#getattachments