I\'m trying to get the data out of a CSV report, located in a specific folder from a shared email and replace the old data from a specific tab in Google Sheets with new ones
I modified your code with these changes so it can work as intended:
1) You were having errors because the csvData variable had to be declared before you can use it. Also, the parseCsv() function is from the Utilities class and you can directly use this class (you were calling it like this: tab.Utilities.parseCsv) [1]. The other problem was that you can't search messages using the message id [2], for that you should make a get request [3].
2) I put an If to validate that the message has an attachment.
3) I changed the condition in your If to validate if it's a csv file with the file extension in its file name, because the gmail API takes a csv file with "application/octet-stream" as mime type (i guess this is because you can open it as a Google Sheets in gmail).
4) I modified how you were getting the message to get the last message of that last thread, previously it was getting the first message of each thread and not the last one.
5) Set the date in the INFO sheet, you can check the formatDate function if you want a specific format [1].
function importCSVFromGmail() {
var threads = GmailApp.search("label:rpt-its-all-data");
var message = threads[0].getMessages().pop();
var attachment = message.getAttachments()[0];
if (attachment != null) {
var attachName = attachment.getName();
// Is the attachment a CSV file
if (attachName.substring(attachName.length-4) === ".csv") {
var id = "1bvENjFYC48LSYDMPtI4FIOKIChiuIrg5O4WRziFeAhU";
var name = "ALLDATA";
var sheet = SpreadsheetApp.openById(id);
var tab = sheet.getSheetByName(name);
var tabInfo = sheet.getSheetByName("INFO");
tabInfo.getRange("B1").setValue(new Date());
// Clear the content of the sheet
tab.clearContents().clearFormats();
var csvData = Utilities.parseCsv(attachment.getDataAsString(), ",");
tab.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
}
}
}
[1] https://developers.google.com/apps-script/reference/utilities/utilities#formatDate(Date,String,String)
[2] https://support.google.com/mail/answer/7190
[3] https://developers.google.com/gmail/api/v1/reference/users/messages/get