Hey everyone, I’m pretty new to Google Apps Script and could really use some guidance.
I’m trying to build a script that can grab CSV files from my email attachments and put the data into different sheets in my Google Spreadsheet. Here’s what I need to do:
- I get emails with CSV attachments every day at the same time
- Each email has a specific sender and subject line that I can use to identify them
- Every email contains exactly one CSV file
- The CSV files have identical names but come in different emails with unique subjects
- I want the script to find these emails, extract the CSV data, and completely replace whatever is already in my spreadsheet sheets
- Each email subject should match up with a specific sheet in my workbook
I found this code online but it keeps throwing an error:
function ImportEmailCSVData() {
var folderLabel = "Daily Reports";
var emailSubjects = ["Report A", "Report B", "Report C"];
var sheetFileId = "98765432100123456789";
for (var x = 0; x < emailSubjects.length; x++) {
var currentSubject = emailSubjects[x];
var targetSheet = currentSubject;
var worksheet = SpreadsheetApp.openById(sheetFileId).getSheetByName(targetSheet);
worksheet.clear();
var emailThreads = GmailApp.search('label:' + folderLabel + ' subject:' + currentSubject);
for (var y = 0; y < emailThreads.length; y++) {
var currentThread = emailThreads[y];
var threadMessages = currentThread.getMessages();
for (var z = 0; z < threadMessages.length; z++) {
var currentMessage = threadMessages[z];
var csvFiles = currentMessage.getAttachmentsByType('application/csv');
if (csvFiles.length > 0) {
var csvFile = csvFiles[0];
var fileContent = Utilities.newBlob(csvFile.getDataAsString()).getDataAsString();
var parsedData = Utilities.parseCsv(fileContent);
worksheet.getRange(worksheet.getLastRow() + 1, 1, parsedData.length, parsedData[0].length).setValues(parsedData);
}
}
}
}
}
The error I’m getting is:
TypeError: currentMessage.getAttachmentsByType is not a function
Can anyone help me figure out what’s wrong with this approach? I’ve been stuck on this for a while and would really appreciate any tips or corrections.