'Export a google sheet to CSV and email as attachment -> sends a CSV attachment but is populated with junk

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).



Solution 1:[1]

Attempted in Jan 2022, including flush(), and it wasn't working for me.

My solution was to simply change the URL format to:

var url = 'https://docs.google.com/spreadsheets/d/' + SpreadSheetId + "/export?format=csv&gid=" + SheetId;

Where

SpeadSheetId = SpreadsheetApp.getActiveSpreadsheet().getId();
SheetId = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Name of your sheet").getSheetId();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharman