如何解决Google Apps Script事件触发器无法发送PDF附件邮件的问题?
问题分析与修复方案
核心问题
你的代码中createPDF函数未返回生成的PDF文件对象,导致sendEmail函数接收到的pdfFile为undefined,无法完成邮件发送。
修复后的完整代码
function afterFormSubmit(e) { const info = e.namedValues; const pdfFile = createPDF(info); sendEmail(e.namedValues['Email Address'][0], pdfFile); } function sendEmail(email, pdfFile) { GmailApp.sendEmail(email, "Here is Your PDF", "Your PDF is Attached.", { attachments: [pdfFile], name: 'Sent From Example' }); } function createPDF(info, filename) { const pdfFolder = DriveApp.getFolderById("1iCVsXmeSMHOpISQslJhX7r842aSHrqos"); const tempFolder = DriveApp.getFolderById("1iCVsXmeSMHOpISQslJhX7r842aSHrqos"); const templateDoc = DriveApp.getFileById("18zVh4aL2Dbt76l6XqwIh2KHeJf6JkY-lMU63MRVOQUM"); const newTempFile = templateDoc.makeCopy(tempFolder); const openDoc = DocumentApp.openById(newTempFile.getId()); const body = openDoc.getBody(); // 替换模板变量 body.replaceText("{date}", info['Timestamp'][0]); body.replaceText("{Email_Address}", info['Email Address'][0]); body.replaceText("{selected_responses}", info['Which of these Positive Attitudes do you struggle with?'][0]); body.replaceText("{Post-Att-01}", info['Choose a positive attitude that you find difficult to maintain.'][0]); body.replaceText("{Happens-When-01}", info['IT HAPPENS WHEN'][0]); body.replaceText("{Triggered-By-01}", info['TRIGGERED BY'][0]); body.replaceText("{RC-Thought #1-01}", info['Rational Counter-Thought #1'][0]); body.replaceText("{RC-Thought #2-01}", info['Rational Counter-Thought #2'][0]); body.replaceText("{RC-Thought #3-01}", info['Rational Counter-Thought #3'][0]); body.replaceText("{Account-Partner-01}", info['Accountability Partner'][0]); body.replaceText("{Post-Att-02}", info['Select another positive attitude that you find difficult to maintain.'][0]); openDoc.saveAndClose(); const blobPDF = newTempFile.getAs(MimeType.PDF); const pdfFile = pdfFolder.createFile(blobPDF).setName("Worksheet Summary"); tempFolder.removeFile(newTempFile); // 关键:返回生成的PDF文件对象 return pdfFile; }
额外检查项
- 触发器权限:确认表单提交触发器使用你的账号创建,且已授权
GmailApp和DriveApp的访问权限。 - 字段匹配:保证表单中"Email Address"字段的名称与
e.namedValues中的键完全一致(注意大小写和空格)。 - 邮件拦截:提醒用户检查邮箱的垃圾邮件/促销文件夹,避免邮件被误拦截。
内容的提问来源于stack exchange,提问作者Jarvis Davis
相关产品推荐
相关产品推荐

