以 Word 格式发送附件在 Google 脚本中不起作用



我已经能够成功发送PDF格式的附件,但是当我尝试以Word格式发送附件时,出现此错误:

"请求失败 https://docs.google.com 返回代码 404。截断的服务器响应:

我已经尝试了这个网站中建议的几种方法,但我就是无法让它工作。

将非常感谢有关此主题的任何帮助。我是谷歌脚本的新手。

这是我的代码:

//=================================================
//  Email Employment Letter as Word format, not PDF
//=================================================
function EmailCertAsWordDoc(requestor, name, newCopyID) {
var email = requestor; 
var id = DocumentApp.openById(newCopyID);
var subject = "Auto-generated Employment Letter"; 
var body = "nnAttached is the Employment Letter that you created for " + name + ". nnnnn ";
var url = "https://docs.google.com/feeds/download/documents/export/Export?id=" + id + "&format=docx&access_token=" + ScriptApp.getOAuthToken();
var docx = UrlFetchApp.fetch(url).getBlob();
if (MailApp.getRemainingDailyQuota() > 0) 
GmailApp.sendEmail(email, subject, {
Body: body,
attachments:[docx]     
});
}

两件事:

  1. 要获取导出 url,您需要使用文件 ID,而不是文件本身 - 在您的情况下它是newCopyID

  2. 不幸的是,将word文件作为附件发送比pdf要复杂一些。要使其正常工作,您可以在驱动器上创建一个 word 文件,然后将其作为电子邮件正文中的 URL 发送。

样本:

function EmailCertAsWordDoc(requestor, name, newCopyID) {
var email = requestor; 
var fileName = DocumentApp.openById(newCopyID).getName();
var subject = "Auto-generated Employment Letter"; 
var body = "nnAttached is the Employment Letter that you created for " + name + ". nnnnn ";
var url = "https://docs.google.com/feeds/download/documents/export/Export?id=" + newCopyID + "&format=docx&access_token=" + ScriptApp.getOAuthToken();
var docx = UrlFetchApp.fetch(url).getBlob();
var file=DriveApp.createFile(docx).setName(fileName).getUrl();
body+=" "+file;
if (MailApp.getRemainingDailyQuota() > 0) 
GmailApp.sendEmail(email, subject, body);
}

这是我遵循ziganotschka建议后的最终工作代码:

//=================================================
//  Email Employment Letter as Word format, not PDF
//=================================================
function EmailCertAsWordDoc(email, name, newCopyID) {
var subject = "Auto-generated Employment Letter"; 
var body = "nnAttached is the Employment Letter that you created for " + name + ". nnnnn ";  
var url = 'https://docs.google.com/feeds/download/documents/export/Export?id=' + newCopyID + '&exportFormat=docx';
var options = {
headers: {
Authorization: "Bearer " + ScriptApp.getOAuthToken()
},
muteHttpExceptions: true
}
var response = UrlFetchApp.fetch(url, options);
var doc = response.getBlob();
//Create the docx file in my TEMP folder in Google Drive and send
var file = DriveApp.createFile(doc).setName('Employment Letter - '+ name + '.docx');
DriveApp.getFolderById('<ID of my TEMP folder in Google Drive>').addFile(file);   
var blob = DriveApp.getFileById(file.getId());
if (MailApp.getRemainingDailyQuota() > 0) 
GmailApp.sendEmail(email, subject, body, {
Body: body,
attachments:[blob]     
});  
//Remove the docx file from the TEMP folder
DriveApp.getFileById(file.getId()).setTrashed(true);
}

最新更新