You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Google Doc以Microsoft Word格式作为邮件附件发送

解决Google Apps Script中Google Doc转Word格式邮件发送的问题

问题根源

你报错的原因是filename是字符串类型(由时间戳和名称拼接而成),而getId()是Google Drive文件对象的专属方法,字符串没有这个方法,直接调用filename.getId()必然抛出错误。

修正步骤与优化方案

1. 正确获取目标Google Doc的ID

在你第一段代码中,已经通过DriveApp.getFilesByName(filename)获取到了文件迭代器,只需从中取出文件对象,再调用getId()即可拿到ID:

// 原代码中已获取compfile文件迭代器
var targetFile = compfile.next(); // 取出对应的文件对象
var compid = targetFile.getId(); // 获取文件ID

2. 简化Word格式导出与邮件发送流程

你之前的EmailCompAsWordDoc函数无需创建临时文件再发送,直接用导出的Blob作为附件即可,减少Drive操作步骤:

function EmailCompAsWordDoc(email, name, docId) {
  var subject = "Word版本的投诉文档"; 
  var body = "\n\n这是您的投诉文档的Microsoft Word版本";  

  // 构造Google Doc转docx的导出链接
  var url = `https://docs.google.com/feeds/download/documents/export/Export?id=${docId}&exportFormat=docx`;
  var options = {
    headers: {
      Authorization: "Bearer " + ScriptApp.getOAuthToken()
    },
    muteHttpExceptions: true
  };

  var response = UrlFetchApp.fetch(url, options);
  var docxBlob = response.getBlob().setName(`Draft Complaint ${name}.docx`); // 直接设置Blob文件名

  if (MailApp.getRemainingDailyQuota() > 0) {
    GmailApp.sendEmail(email, subject, body, {
      attachments: [docxBlob] // 直接传入Blob作为邮件附件
    });
  }
}

3. 整合代码调用

把修正后的ID获取和函数调用整合到原业务流程中:

doc.saveAndClose(); // 完成从Sheet到Doc的内容转移

var filename = ts + "-" + c_name1;
var compfile = DriveApp.getFilesByName(filename);

if (!compfile.hasNext()) {
  console.error("无法找到文件:" + filename);
  return;
}

// 获取目标文件ID
var targetFile = compfile.next();
var compid = targetFile.getId();

// 调用Word格式邮件发送函数
EmailCompAsWordDoc(em, c_name1, compid);

额外注意事项

  • 确保脚本拥有Google Drive和Gmail的授权权限,首次运行时会弹出授权提示,需允许相关权限。
  • 若导出失败,可将muteHttpExceptions设为false,查看具体错误信息排查权限或文件访问问题。

内容的提问来源于stack exchange,提问作者Anthony

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 17:40:23