[英]Google sheet script suddenly stops working and fails to send email attachment due to attachment authentication failure
軟件:谷歌表格和谷歌應用腳本
大家好,我一直在向自己發送測試電子郵件,其中包含我的谷歌表格中的附件。 他們進展順利。 然后我跳了一天,開始收到身份驗證錯誤。 我已經嘗試了幾種不同的修復方法,但我仍然卡住了。 如果我什么都不做,我不知道為什么它會壞掉。 無論如何,我現在正在改變一些東西來嘗試修復它。
它可以讓我發送純電子郵件,但是當我嘗試附加 pdf 或 xsls 文件時,它會失敗。 這在它停止工作之前工作得很好......設置'muteHttpExceptions':true,允許email發送,但附件是空的/損壞的。
您是否知道通過 email 以 pdf 格式發送特定表格的更好方法,或者解決此問題的方法?
代碼:
function SampleEmail() {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheetgId = ss.getActiveSheet().getSheetId();
var sheetName = ss.getName();
var email = "test@gmail.com";
var subject = "Important Info!";
var body = "Test email.";
var url = "https://docs.google.com/spreadsheets/d/" + ssID + "/export?" + "format=pdf" + "&gid=" + sheetgId + "&portrait=true" + "&exportFormat=pdf";
var token = ScriptApp.getOAuthToken();
var result = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
},
'muteHttpExceptions': false
});
var contents = result.getContent();
GmailApp.sendEmail(email, subject, body, { attachments: [{ fileName: sheetName + ".pdf", content: contents, mimeType: "application//pdf" }] });
}
錯誤信息:
5:58:33 AM Error
Exception: Request failed for https://docs.google.com returned code 401. Truncated server response: <HTML>
<HEAD>
<TITLE>Unauthorized</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Unauthorized</H1>
<H2>Error 401</H2>
</BODY>
</HTML>
(use muteHttpExceptions option to examine full response)
SampleEmail @ code.gs:108
解決方案:(感謝@Amit_Singh 的建議。)
嘗試運行此 function 將您的谷歌表格作為 pdf 發送到您的谷歌驅動器。 這使用 getOAuthToken() 為我清除了緩存或其他內容,並允許原始腳本進行身份驗證並正確發送 email 附件。 這是 function:
function convertSheetToPDF() {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheetgId = ss.getActiveSheet().getSheetId();
var sheetId = sheetgId; // "2SqIXLiic6-gjI2KwQ6OIgb-erbl3xqzohRgE06bfj2c";
var spreadsheetName = "My Spreadsheet";
var destination = DriveApp.createFolder('new folder');
//var destination = DriveApp.getFolderById("1vFL98cgKdMHLNLSc542pUt4FMRTthUvL");
//var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key=" + sheetId + "&exportFormat=xlsx";
var url = "https://docs.google.com/spreadsheets/d/" + ssID + "/export?" + "format=pdf" + "&gid=" + sheetgId + "&portrait=true" + "&exportFormat=pdf";
var params = {
method: "get",
headers: { "Authorization": "Bearer " + ScriptApp.getOAuthToken() },
muteHttpExceptions: false
};
var blob = UrlFetchApp.fetch(url, params).getBlob();
blob.setName(spreadsheetName + ".xlsx");
destination.createFile(blob);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.