通过Apps Script添加Google Forms生成的Google Doc邮件附件问题
修正Google Apps Script邮件附件问题
原代码的核心问题有两个:
- 在替换文档内容之前就生成了PDF Blob,导致附件是未修改的模板内容
- 发送邮件的操作在文档保存关闭之前执行,修改后的内容还没写入文件
以下是修正后的完整代码:
function autoFillGoogleDocFromForm(e) { var student = e.values[4]; var grade = e.values[5]; var date = e.values[2]; var staff = e.values[6]; var locationOfIncident = e.values[7]; var timeOfIncident = e.values[3]; var othersInvolvedTeachersStaff = e.values[8]; var othersInvolvedStudents = e.values[9]; var othersInvolvedWitnesses = e.values[10]; var explanationOfIncident = e.values[11]; var actionsTakenByStaffPriorToReferral = e.values[12]; var officeDisciplineReferralTemplate = DriveApp.getFileById("1X2OL1TjIq4SH92kUN2xhSeyjkAF_OqqBXeGAbgI-7KU"); var responses = DriveApp.getFolderById("12NhsRcegOH_ZFYtMmVoT44pYdBs_NlLL"); var copy = officeDisciplineReferralTemplate.makeCopy(date + ', ' + student, responses); var doc = DocumentApp.openById(copy.getId()); var body = doc.getBody(); // 执行所有文本替换 body.replaceText("<<Student>>", student); body.replaceText("<<Grade>>", grade); body.replaceText("<<Date>>", date); body.replaceText("<<Staff>>", staff); body.replaceText("<<Location of Incident>>", locationOfIncident); body.replaceText("<<Time of Incident>>", timeOfIncident); body.replaceText("<<Teachers/Staff>>", othersInvolvedTeachersStaff); body.replaceText("<<Student Directly Involved>>", othersInvolvedStudents); body.replaceText("<<Witnesses>>", othersInvolvedWitnesses); body.replaceText("<<Explanation of Incident>>", explanationOfIncident); body.replaceText("<<Actions Taken By Staff Prior to Referral>>", actionsTakenByStaffPriorToReferral); // 先保存并关闭文档,确保修改生效 doc.saveAndClose(); // 从已保存的文件生成PDF Blob var blob = copy.getAs('application/pdf'); // 发送邮件,附件使用最新的PDF MailApp.sendEmail( "jscoggins@paden.k12.ok.us", 'Office Discipline Referral', 'Office Discipline Referral', {attachments: [blob]} ); }
关键修改说明:
- 将
doc.saveAndClose()移到文本替换完成后、生成Blob之前,确保所有修改内容被写入文件 - 从已保存的复制文件(
copy)而非打开的文档对象获取PDF Blob,保证附件是替换后的最新内容 - 移除了无意义的
Utilities.newBlob代码块
内容的提问来源于stack exchange,提问作者Jay Scoggins
相关产品推荐
相关产品推荐

