我正在嘗試將 Google 作業表匯出為 excel 檔案,然后將其附加到 sendGrid 電子郵件。電子郵件沒有附件就通過了。
我認為這與base64encoding有關,但不確定我哪里出錯了。
這是我匯出 excel 并嘗試將其發送到 sendGrid 函式的代碼:
function getGoogleSpreadsheetAsExcel(){
try {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var blankSS = 'xxxxxxxxxxxxxxxxxxxxxxx';
var donations = ss.getSheetByName('Donations');
var getrange = donations.getDataRange();
var data = getrange.getValues();
var header = data[0].slice(0, 13);
var dataArray = [];
dataArray.push(header);
for(var i=0;i<data.length;i ){
const sent = data[i][14];
if(sent){
continue;
}else{
const row = data[i];
row.splice(-2);
dataArray.push(row);
}
}
var temp = SpreadsheetApp.openById(blankSS).getActiveSheet();
if(dataArray.length > 1){
dataArray.forEach((row) => temp.appendRow(row));
var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key=" blankSS "&exportFormat=xlsx";
var params = {
method : "get",
headers : {"Authorization": "Bearer " ScriptApp.getOAuthToken()}
};
var blob = UrlFetchApp.fetch(url, params).getBlob().getBytes();
var doc = Utilities.base64EncodeWebSafe(blob);
const subject = "Activity Report";
const body = "Please see attached spreadsheet of recent purchases.";
sendEmailWithSendGrid(subject,body,doc);
donations.getRange(2, 15, donations.getLastRow()-1).setValue('sent');
}
temp.clear()
}
catch (f) {
MailApp.sendEmail("[email protected]", "Script Error", f);
}
}
這是 sendGrid 函式:
function sendEmailWithSendGrid(subject,body,attachments){
const key = 'SG.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
const url = 'https://api.sendgrid.com/v3/mail/send';
var payload = {
"personalizations": [{"to": [{"email": "[email protected]"}]}],
"from": {"email": "[email protected]"},
"subject": subject,
"content": [{ "type": "text/plain", "value": body }],
"attachment": [{"content": attachments, "type": "text/plain" , "filename": "testExcel.xlsx"}]
};
var options = {
"method" : "post",
"payload" : JSON.stringify(payload)
};
options.headers = {
"Authorization" : "Bearer " key,
"Content-Type" : "application/json"
};
var res = UrlFetchApp.fetch(url, options);
Logger.log(JSON.stringify(res.getResponseCode()));
}
uj5u.com熱心網友回復:
當我查看SendGrid API的郵件發送請求正文的官方檔案時,似乎鍵名是attachments并且也是contentBase64 編碼的內容。那么下面的修改呢?
從:
"attachment": [{"content": attachments, "type": "text/plain" , "filename": "testExcel.xlsx"}]
到:
"attachments": [{"content": attachments, "type": "text/plain" , "filename": "testExcel.xlsx"}]
而且,在您的情況下,var doc = Utilities.base64EncodeWebSafe(blob);可能是var doc = Utilities.base64Encode(blob);. 所以也請測驗一下。
參考:
- SendGrid API 的郵件發送
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/408567.html
標籤:
上一篇:只要任務未完成且專案未積壓,就向任務所有者發送電子郵件
下一篇:基于列拆分作業表
