如何修改Google Apps Script,将自动生成的Google Docs以.docx发送给受访者
如何将Google Form响应生成的文档转为Word(.docx)附件发送邮件
核心修改是替换原脚本中PDF导出的逻辑,改用Google Drive的文件导出能力生成docx格式的Blob,再作为邮件附件发送。以下是具体修改步骤和完整示例:
关键修改点
Google Docs的DocumentApp对象不支持直接导出为docx,需要通过DriveApp获取文件对象,调用getAs()方法并传入docx对应的MIME类型:
application/vnd.openxmlformats-officedocument.wordprocessingml.document
完整修改后的脚本示例
function onFormSubmit(e) { // 1. 获取表单响应数据 var responses = e.response.getItemResponses(); var respondentEmail = e.response.getRespondentEmail(); // 跳过无邮箱的情况 if (!respondentEmail) { Logger.log("受访者未提供邮箱,终止发送"); return; } // 2. 复制模板文档并替换内容 var templateDocId = "你的模板文档ID"; // 替换为你的模板ID var newDocName = "响应文档_" + new Date().toLocaleString(); var newDoc = DriveApp.getFileById(templateDocId).makeCopy(newDocName); var doc = DocumentApp.openById(newDoc.getId()); var body = doc.getBody(); // 替换模板占位符(请根据你的模板调整占位符格式,比如{{姓名}}) for (var i = 0; i < responses.length; i++) { var itemTitle = responses[i].getItem().getTitle(); var responseValue = responses[i].getResponse(); body.replaceText("{{" + itemTitle + "}}", responseValue); } doc.saveAndClose(); // 3. 生成docx格式Blob(核心修改部分) var docxBlob = DriveApp.getFileById(newDoc.getId()) .getAs("application/vnd.openxmlformats-officedocument.wordprocessingml.document") .setName("你的响应文档.docx"); // 设置附件文件名 // 4. 发送带docx附件的邮件 MailApp.sendEmail({ to: respondentEmail, subject: "你的表单响应已生成Word文档", body: "您好,附件是根据您的表单响应生成的Word文档,请查收。", attachments: [docxBlob] }); // 可选:自动删除生成的Google Docs文件(如果不需要保留) // DriveApp.getFileById(newDoc.getId()).setTrashed(true); }
注意事项
- 权限授权:首次运行脚本时,会请求Drive和Mail服务的权限,需要按提示完成授权
- 模板匹配:确保模板中的占位符(比如
{{姓名}})和表单的问题标题完全一致,否则无法正确替换内容 - MIME类型正确性:必须使用指定的docx MIME类型,否则会生成无效文件
内容的提问来源于stack exchange,提问作者Gandy Des Ardy
相关产品推荐
相关产品推荐

