Send E-mail with Excel file converted from Spreadsheet

This sample script sends an e-mail with an Excel file exported from Spreadsheet as an attachment file.

function excelSender() {
  var sheetID = [Sheet ID];
  var xlsxName = [Excel file name];
  var params = {
    "headers" : {Authorization: "Bearer [Retrieved AccessToken]"},
    "muteHttpExceptions" : true
  };
  var dUrl = "https://www.googleapis.com/drive/v3/files/" + sheetID + "/export?mimeType=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
  var xlsxlFile = UrlFetchApp.fetch(dUrl, params).getBlob().setName(xlsxName);
  MailApp.sendEmail({
    to: [Mail address],
    subject: "sample subject",
    body: "sample body",
    attachments: [xlsxlFile]
  });
}

Is ScriptApp.getOAuthToken() unstable? When it creates new GAS project, it can be used. But when the time has elapsed, the script cannot be used. On the other hand, when an access token manually retrieves without getOAuthToken(), it can be used stably. The scopes I used are https://www.googleapis.com/auth/drive and https://www.googleapis.com/auth/drive.file. I don’t know about this reason.

 Share!