I'm attempting to export a specific sheet to CSV format and then email the csv file as an attachment in email. My code ends up emailing a CSV attachment okay, but the content of the csv attachment is bogus. I log the URL and then test this directly from the browser. It seems to find the correct named sheet. Is there a way to verify the result of UrlFetchApp.fetch()
? Can anyone advise what I'm doing wrong here?
var ss = SpreadsheetApp.getActiveSpreadsheet();
var convertedSheet = ss.getSheetByName(dateToProcess);
if (convertedSheet != null) {
var sheetName = convertedSheet.getName();
Logger.log("Sheet Name:", sheetName); // logs correct sheet name
// this approach to constructing url is suggested in a similar post instead of using "getUrl()
var url = 'https://docs.google.com/spreadsheets/d/'+ SpreadsheetApp.getActiveSpreadsheet().getId();
url += '#gid=';
url += convertedSheet.getSheetId();
url += "/export?exportFormat=csv&format=csv";
Logger.log("URL: ", url); //this brings up correct sheet when I paste the url in the browser. It does not trigger a download of it in the browser - should it be?
var email = Session.getActiveUser().getEmail();
Logger.log(email); //correct
var subject = "New Submission is Attached! ";
var body = "You have a new submission!";
var requestData = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
var result = UrlFetchApp.fetch(url, requestData).getBlob();
MailApp.sendEmail(email,
subject,
body,
{
attachments: [{
fileName: sheetName + ".csv",
content: result.getBytes(),
mimeType: "text/csv"
}]
});
}
In the CSV that is sent as an attachment, the cells are populated with what appears to be generated code (delimited by all the commas in the code).