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

如何用GmailApp.createDraft()将Sheets文件添加为Drive插入式面板到邮件草稿?

问题解答

不行,GmailApp.createDraft() 函数本身无法直接实现你想要的那种Drive文件内嵌面板样式(即手动「通过Drive插入文件」生成的卡片视图),原因如下:

  • 该函数的attachments参数仅支持添加两种类型内容:
    1. 本地/导出的文件附件(比如将Sheets导出为PDF/Excel格式后添加)
    2. Drive文件的普通链接(无法渲染为内嵌面板)

要实现目标效果,你需要使用Advanced Gmail Service(基于Gmail REST API),它支持创建带内嵌Drive文件卡片的邮件草稿。

实现步骤与代码示例

  1. 启用Advanced Gmail Service
    在脚本编辑器中:依次点击「扩展程序」→「Apps Script」→「服务」→找到「Gmail API」并启用(首次启用需关联Google Cloud Console中的对应API,按提示操作即可)。

  2. 编写代码
    替换代码中的YOUR_SHEET_FILE_ID为目标Sheets文件的Drive ID:

    function createDraftWithDriveCard() {
      const recipient = 'mike@example.com';
      const subject = 'Attachment example';
      const bodyText = 'Please see attached file.';
      
      // 目标Sheets文件的Drive ID
      const sheetDriveId = 'YOUR_SHEET_FILE_ID';
      const targetFile = DriveApp.getFileById(sheetDriveId);
      
      // 通过Advanced Gmail Service创建带内嵌Drive卡片的草稿
      const draft = Gmail.Users.Drafts.create({
        message: {
          payload: {
            headers: [
              { name: 'To', value: recipient },
              { name: 'Subject', value: subject }
            ],
            parts: [
              // 纯文本邮件内容
              {
                mimeType: 'text/plain',
                body: {
                  data: Utilities.base64EncodeWebSafe(bodyText)
                }
              },
              // 内嵌Drive文件卡片
              {
                mimeType: targetFile.getMimeType(),
                filename: targetFile.getName(),
                body: {
                  attachmentId: sheetDriveId
                },
                headers: [
                  { name: 'Content-Disposition', value: `inline; filename="${targetFile.getName()}"` }
                ]
              }
            ]
          }
        }
      }, 'me');
      
      console.log(`草稿已创建,ID: ${draft.id}`);
    }
    

效果说明

运行上述代码后,生成的Gmail草稿中,目标Sheets文件会以你期望的内嵌面板样式展示,和手动通过Drive插入文件的效果完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 18:15:05