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

如何通过App Script开发的Gmail addon从Google Drive下载文件?

实现Gmail Add-on点击按钮下载Drive中的PDF文件

核心思路

Gmail Add-on的Card Services没有直接的下载组件,我们可以通过生成Drive文件的临时下载链接,再通过打开链接触发浏览器下载来实现。具体分三步:绑定按钮点击事件、服务器端获取文件下载链接、打开链接触发下载。

步骤1:构建带下载按钮的Card

在你的Card构建逻辑中,添加一个按钮,绑定服务器端函数处理下载请求。

function buildGmailAddonCard(e) {
  // 获取当前邮件ID,用于关联对应的PDF文件
  const messageId = e.gmail.messageId;
  
  // 创建下载按钮
  const downloadButton = CardService.newTextButton()
    .setText("下载邮件PDF")
    .setOnClickAction(CardService.newAction()
      .setFunctionName("handleDownloadClick")
      .setParameters({messageId: messageId})); // 传递邮件ID到服务器端
  
  // 构建Card并添加按钮
  const section = CardService.newCardSection().addWidget(downloadButton);
  const card = CardService.newCardBuilder().addSection(section).build();
  
  return [card];
}

步骤2:服务器端处理点击事件,生成下载链接

编写handleDownloadClick函数,根据邮件ID找到对应的Drive文件ID,生成可直接下载的链接,返回打开链接的操作。

function handleDownloadClick(e) {
  const messageId = e.parameters.messageId;
  
  // 替换成你关联邮件ID和Drive文件ID的逻辑
  // 示例:从用户属性中获取之前保存的对应PDF文件ID
  const properties = PropertiesService.getUserProperties();
  const pdfFileId = properties.getProperty(`pdf_${messageId}`);
  
  if (!pdfFileId) {
    return CardService.newActionResponseBuilder()
      .setNotification(CardService.newNotification()
        .setText("未找到对应的PDF文件"))
      .build();
  }
  
  // 生成Drive文件的直接下载链接
  const downloadUrl = `https://drive.google.com/uc?export=download&id=${pdfFileId}`;
  
  // 返回打开链接的操作,触发浏览器下载
  return CardService.newActionResponseBuilder()
    .setOpenLink(CardService.newOpenLink()
      .setUrl(downloadUrl)
      .setOpenAs(CardService.OpenAs.FULL_SIZE)
      .setOnClose(CardService.OnClose.NOTHING))
    .build();
}

步骤3:确保文件权限正确

生成PDF文件时,要保证当前用户有权限访问:

  • 若在用户个人Drive创建文件,默认用户拥有所有权,无需额外设置;
  • 若在共享Drive或其他位置创建,需添加用户访问权限:
// 创建PDF文件后添加权限示例
const pdfFile = DriveApp.createFile(blob);
pdfFile.addEditor(Session.getActiveUser().getEmail()); // 赋予编辑权限
// 或设置为仅查看:pdfFile.addViewer(Session.getActiveUser().getEmail());

注意事项

  • 确保Add-on已申请https://www.googleapis.com/auth/drive.file或https://www.googleapis.com/auth/drive的OAuth权限,根据文件存储位置选择;
  • 若文件较大,可在下载链接后追加&confirm=t参数,避免浏览器的安全确认弹窗;
  • 关联邮件ID与Drive文件ID的逻辑可灵活调整,比如用邮件ID作为文件名前缀,通过Drive搜索获取文件ID。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 06:15:09