Google Apps Script表单场景带PDF附件发邮件报附件参数无效
报错原因拆解
- 附件类型不匹配:
GmailApp.sendEmail的attachments参数仅接受PDF格式的Blob对象数组,原代码直接将Google Drive的File对象传入参数,不符合接口格式要求。 - 手动触发时参数缺失:直接空参手动运行sendEmail函数时,没有传入函数要求的
currentEmail和pdfFile两个实参,此时pdfFile为undefined,构建的attachments:[pdfFile]实际是attachments:[undefined],直接触发参数校验报错,对应当前报错提示里的line 36位置。 - 函数逻辑错位:sendEmail开头接收的两个入参(当前学生邮箱、对应生成的PDF文件),在原代码的for循环里被
var currentEmail = ss.getRange(i, 6).getValue();直接覆盖;同时循环会从表格第2行遍历到最后一行,给所有历史提交记录的学生重复发送邮件,且所有收件人收到的都是同一份最新生成的PDF,和自己对应的材料完全不匹配。 - 冗余操作拖慢运行:原代码中激活Sheet2的操作无实际作用,在自动化触发场景下还会额外消耗脚本运行配额。
具体修复方案
- 调整附件传递格式:将传入的Drive File对象通过
getAs(MimeType.PDF)转为Blob对象,满足Gmail接口的参数要求。 - 删掉冗余的全表循环逻辑:sendEmail不需要遍历整个Sheet2,只需要处理当前表单提交对应的单条记录即可,避免重复发信。
- 删除无意义的工作表激活操作,减少不必要的权限调用和资源消耗。
- 手动测试时注意:如果要单独运行sendEmail做测试,需要提前构造好测试用的邮箱、PDF文件实参传入函数,不要直接空参运行。
修复后参考代码
function afterFormSubmit(e) { const info = e.namedValues; const pdfFile = createPDF(info); const entryRow = e.range.getRow(); const ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2"); ws.getRange(entryRow, 7).setValue(pdfFile.getUrl()); ws.getRange(entryRow, 8).setValue(pdfFile.getName()); // 调用sendEmail时传入当前学生邮箱、生成的PDF文件、学生姓名 sendEmail(e.namedValues['Student Email'][0], pdfFile, info['Student name'][0]); } function sendEmail(currentEmail, pdfFile, studentName){ const templateText = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Template").getRange(1, 1).getValue(); const messageBody = templateText.replace("{recipient}", studentName); const subjectLine = "Congratulations on your merit! " + studentName; // 将Drive File对象转为PDF Blob,作为合法附件传入 const pdfBlob = pdfFile.getAs(MimeType.PDF); GmailApp.sendEmail(currentEmail, subjectLine, messageBody, { attachments: [pdfBlob], name: 'St Clare Merits' }); } function createPDF(info) { const pdfFolder = DriveApp.getFolderById("1WIgfR7YESk6fcRPbzKa_Gsi_yp3-gemg"); const tempFolder = DriveApp.getFolderById("1QgnNLCbmm1z9RvPQCjA-vSnuw-P1Fw4X"); const templateDoc = DriveApp.getFileById("1fh5uRKQ9WZOY-ngXK0sOxH85UX_HHR1HYDefQhjfZVI"); const newTempFile = templateDoc.makeCopy(tempFolder); const openDoc = DocumentApp.openById(newTempFile.getId()); const body = openDoc.getBody(); body.replaceText("{name}", info['Student name'][0]); body.replaceText("{reason}", info['Reason for Merit'][0]); body.replaceText("{Sname}", info['Staff Name'][0]); body.replaceText("{Date}", info['Date'][0]); openDoc.saveAndClose(); const blobPDF = newTempFile.getAs(MimeType.PDF); const pdfFile = pdfFolder.createFile(blobPDF).setName(info['Student name'][0]+ " " + new Date()); newTempFile.setTrashed(true); return pdfFile; }
补充说明
- 原代码中遍历全表计算剩余发信额度的逻辑可以直接删除,系统会在每日发信额度不足时自动抛出报错,不需要额外逻辑占用运行资源。
- 后续如果需要给历史补发的场景,可以单独写遍历函数,指定需要补发的行号范围,不要把补发逻辑和单条自动发信的逻辑混在一起。
内容的提问来源于stack exchange,提问作者Anfernee
相关产品推荐
相关产品推荐

