I'm trying to get data from a csv file in attachment in my my Gmail, parse it and import it with Google Script in Google Sheets.
Problem is when I get content type of my attachment I have this message "application/octet-stream" and not CSV so I think algorithm doesn't keep on in if condition.
Do you have suggestion why I don't get right file type ?
Big thanks !
Here's the code :
function importCSVFromGmail() {
var threads = GmailApp.search("Money Transfer Tracking - Tickets");
var message = threads[0].getMessages()[0];
var attachment = message.getAttachments()[0];
console.log(attachment.getContentType())
// 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);
}
}
If you want to use if (attachment.getContentType() === "text/csv") {}
, it is required to set the mimeType of text/csv
. Also if there is the possibility that attachment
has various mimeTypes, how about this modification?
If the attachment file has the filename including the extension, how about this modification? I think that this is more suitable way for your situation, because the attachment files of email often have the filename and the extension.
var attachment = message.getAttachments()[0];
attachment.setContentTypeFromExtension(); // Added
If the attachment file has the filename without including the extension, how about this modification?
var attachment = message.getAttachments()[0];
attachment.setContentType("text/csv"); // Added
If this was not the result you want, I apologize.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.