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

Google Apps Script:为表单提交邮件添加PDF附件代码求助

Google表单提交后发送带PDF附件邮件的实现方案

需求说明

现有关联Google Form的Apps Script可实现提交后发送自定义邮件,需新增功能:读取表单中新增的PDF上传字段,将上传的PDF作为附件随邮件发送。

原基础运行脚本(无附件功能)

function onFormSubmit(e) {
  const responses = e.response.getItemResponses();
  let emailContent = "表单提交内容:\n";
  
  responses.forEach(response => {
    emailContent += `${response.getItem().getTitle()}: ${response.getResponse()}\n`;
  });

  MailApp.sendEmail({
    to: "收件人邮箱@example.com",
    subject: "新表单提交通知",
    body: emailContent
  });
}

常见错误写法(直接传入URL)

很多人会尝试直接用上传字段返回的URL作为附件,这是无效的:

function onFormSubmit(e) {
  const pdfItem = e.response.getItemResponses().find(r => r.getItem().getTitle() === "上传PDF");
  const pdfUrl = pdfItem.getResponse();

  // 错误:URL无法直接作为附件传入MailApp
  MailApp.sendEmail({
    to: "收件人邮箱@example.com",
    subject: "新表单提交通知",
    body: "含PDF附件",
    attachments: [pdfUrl]
  });
}

正确实现代码

前提配置

先在Google Form中新增「文件上传」字段,设置仅允许PDF格式上传。

修改后的完整脚本

function onFormSubmit(e) {
  const formResp = e.response;
  const itemResps = formResp.getItemResponses();
  let emailBody = "新表单提交详情:\n\n";
  let pdfAttach = null;

  itemResps.forEach(itemResp => {
    const itemTitle = itemResp.getItem().getTitle();
    const respVal = itemResp.getResponse();

    // 处理普通文本/选择类字段
    if (itemResp.getItem().getType() !== FormApp.ItemType.FILE_UPLOAD) {
      emailBody += `${itemTitle}: ${respVal}\n`;
    }
    // 处理PDF上传字段(请替换为你的表单字段标题)
    else if (itemTitle === "上传PDF") {
      const fileIds = respVal;
      // 取第一个上传的PDF(支持多文件的话可遍历数组)
      if (fileIds.length > 0) {
        const pdfFile = DriveApp.getFileById(fileIds[0]);
        // 验证文件类型确保是PDF
        if (pdfFile.getMimeType() === MimeType.PDF) {
          pdfAttach = pdfFile.getAs(MimeType.PDF);
        }
      }
    }
  });

  const emailOpts = {
    to: "收件人邮箱@example.com",
    subject: "表单提交通知(含PDF附件)",
    body: emailBody
  };

  // 存在有效PDF时添加附件
  if (pdfAttach) {
    emailOpts.attachments = [pdfAttach];
  }

  MailApp.sendEmail(emailOpts);
}

关键要点

  1. 文件ID而非URL:表单文件上传字段的getResponse()返回的是文件ID数组,必须通过DriveApp.getFileById()获取文件对象
  2. 类型验证:添加MIME类型检查,避免非PDF文件被误传
  3. 权限授权:首次运行脚本时需授权访问Google Drive,否则无法读取上传的文件
  4. 多文件支持:若需支持多PDF上传,可遍历fileIds数组,将所有符合条件的文件添加到attachments数组中

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 04:54:56