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

Google Script无法发送邮件求助:表单提交后PDF正常但邮件未发

Google Script邮件发送失败的问题排查与修复

核心问题分析

  • createPDF函数无返回值:函数成功生成PDF文件后,未将文件对象返回给调用者,导致sendEmail和sendEmail2接收的pdfFile参数为undefined,附件无法正常添加,直接引发邮件发送失败。
  • 字符串拼接运算符错误:sendEmail2中使用&进行字符串拼接,这是JavaScript的位运算符号,而非字符串连接符,会导致邮件正文内容异常,可能触发发送逻辑报错。

修复后的完整代码

function afterFormSubmit(e) { 
    const info = e.namedValues;
    const pdfFile = createPDF(info);

    sendEmail(e.namedValues['Email Address'][0], pdfFile);
    sendEmail2(e.namedValues['Name'][0], pdfFile);
}

function sendEmail(email, pdfFile){
  GmailApp.sendEmail(
    email,
    "Cutting Edge Renovation and Painting, LLC - Acknowledgement Form Completed",
    "Please find a copy of the Cutting Edge Renovation and Painting, LLC Acknowledgement form you completed for your records.",
    {
      attachments: [pdfFile],
      name: 'Cutting Edge Renovation and Painting, LLC'
    }
  );
}

function sendEmail2(clientName, pdfFile){
  GmailApp.sendEmail(
    "Service@cuttingedgereno.com",
    "Cutting Edge Renovation and Painting, LLC - Client Completed the Acknowledgement Form",
    `${clientName} has completed the Acknowledgement form`,
    {
      attachments: [pdfFile],
      name: 'Cutting Edge Renovation and Painting, LLC'
    }
  );
}

function createPDF(info){
  const pdfFolder = DriveApp.getFolderById("1N2QTvSJgRMtBx7TzCIKUWc6o3JOhfuGU");
  const tempFolder = DriveApp.getFolderById("1WpbEOn_zH1IdvA_PkvxeDPnMXJVVMWQj"); 
  const templateDoc = DriveApp.getFileById("1QMHSL1CFb_2srVDd1YZlQEmGMTx0sHm7NGjWBZpnccE");
  const newTempFile = templateDoc.makeCopy(tempFolder);
  const openDoc = DocumentApp.openById(newTempFile.getId());
  const body = openDoc.getBody();

  body.replaceText("{Name}", info['Name'][0]);
  body.replaceText("{Address}", info['Job Address'][0]);
  body.replaceText("{Photo}", info['Photo Release'][0]);
  body.replaceText("{Access}", info['Home Access'][0]);
  body.replaceText("{Parking}", info['Parking'][0]);
  body.replaceText("{Parking2}", info['Parking Permit'][0]);
  body.replaceText("{Signature}", info['Signature'][0]);
  body.replaceText("{Phone}", info['Phone Number'][0]);
  body.replaceText("{Date}", info['Timestamp'][0]);

  openDoc.saveAndClose();

  const blobPDF = newTempFile.getAs(MimeType.PDF);
  const pdfFile = pdfFolder.createFile(blobPDF).setName(info['Name'][0]);
  
  // 关键修复:返回生成的PDF文件对象
  return pdfFile;
}

额外优化建议

  • 权限验证:首次运行脚本时,需完成GmailApp的授权流程,确保脚本拥有发送邮件的权限。
  • 错误日志排查:若修复后仍发送失败,可通过脚本编辑器「查看」→「日志」功能,查看具体错误信息(如邮箱格式错误、Drive权限不足等)。
  • 临时文件清理:在createPDF函数末尾添加newTempFile.setTrashed(true);,自动删除临时生成的文档,避免占用Drive存储空间。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 16:30:07