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

如何在Google Apps Script中发送Google Drive文件夹内的附件?

问题修复方案

核心报错常见诱因

  • 权限配置缺失:脚本未授予Drive读取、Gmail发送对应权限,OAuth作用域未正确配置
  • 方法调用不符合规范:附件参数格式、文件blob获取逻辑错误
  • 格式适配问题:Google Workspace原生文件(Docs、Sheets、Slides等)无法直接作为附件发送,需先导出为通用格式
  • 大小超限:Gmail单次发送附件总大小上限为25MB,超出会触发报错

可直接运行的参考实现

function addDriveFilesAsAttachments() {
  // 替换为目标文件夹ID(从Drive文件夹地址栏获取)
  const FOLDER_ID = "你的文件夹ID";
  const targetFolder = DriveApp.getFolderById(FOLDER_ID);
  const fileIterator = targetFolder.getFiles();
  const attachmentList = [];

  while (fileIterator.hasNext()) {
    const currentFile = fileIterator.next();
    const mimeType = currentFile.getMimeType();

    // 适配Google Workspace原生文件导出逻辑,可按需修改导出格式
    if (mimeType === "application/vnd.google-apps.document") {
      attachmentList.push(currentFile.getAs(MimeType.PDF).setName(`${currentFile.getName()}.pdf`));
    } else if (mimeType === "application/vnd.google-apps.spreadsheet") {
      attachmentList.push(currentFile.getAs(MimeType.MICROSOFT_EXCEL).setName(`${currentFile.getName()}.xlsx`));
    } else if (mimeType === "application/vnd.google-apps.presentation") {
      attachmentList.push(currentFile.getAs(MimeType.PDF).setName(`${currentFile.getName()}.pdf`));
    } else {
      // 其他通用格式文件直接读取
      attachmentList.push(currentFile.getBlob());
    }
  }

  // 示例:调用Gmail发送带附件邮件,attachments参数直接传入上面生成的列表即可
  GmailApp.sendEmail(
    "recipient@example.com",
    "带Drive附件的测试邮件",
    "邮件正文内容",
    { attachments: attachmentList }
  )
}

权限配置修复

如果运行时报权限相关错误,按如下步骤配置:

  1. 打开Apps Script编辑器左侧「项目设置」页面
  2. 勾选「在编辑器中显示appsscript.json 清单文件」
  3. 回到编辑器打开appsscript.json文件,添加以下作用域配置:
{
  "timeZone": "Asia/Shanghai",
  "dependencies": {},
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8",
  "oauthScopes": [
    "https://www.googleapis.com/auth/drive.readonly",
    "https://www.googleapis.com/auth/gmail.send"
  ]
}
  1. 保存后重新运行脚本,重新授权即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 01:36:03