基于Google表单选项的AppScript条件发信故障求助
问题修复:Google Apps Script 条件邮件发送逻辑错误
问题根源
原代码中第二个if语句错误嵌套在第一个if内部,导致只有当data[4]等于目标值时才会进入该分支,但此时第二个if的条件必然不成立,永远不会触发向emailaddy2@test.com的邮件发送。同时,发给emailaddy3@test.com的逻辑也被嵌套,导致只有选中特定选项时才会发送,违反了「所有提交均需发送」的规则。
另外,通过toString()再split(",")处理表单数据存在风险——如果表单回答中包含逗号,会导致数据拆分错误,建议直接通过数组索引访问表单行数据。
修正后的代码
function variedEmails() { var aSheet = SpreadsheetApp.getActiveSpreadsheet(); // 直接获取最后一行数据,无需转字符串拆分 var lastRowData = aSheet.getRange(aSheet.getLastRow(), 1, 1, aSheet.getLastColumn()).getValues()[0]; var headers = aSheet.getRange(1, 1, 1, aSheet.getLastColumn()).getValues()[0]; // 处理时间戳,移除时区部分 var formatTimestamp = function(timestampStr) { var parts = timestampStr.split(" "); return parts.slice(0, 4).join(" "); }; lastRowData[0] = formatTimestamp(lastRowData[0]); lastRowData[9] = formatTimestamp(lastRowData[9]); // 构建HTML表格 var table = "<table style='border: 1px solid; border-collapse: collapse'>"; for (var i = 0; i < headers.length; i++) { if (lastRowData[i] !== "") { table += "<tr style='border: 1px solid'>" + "<td style='border: 1px solid; padding: 8px'>" + headers[i] + "</td>" + "<td style='border: 1px solid; padding: 8px'>" + lastRowData[i] + "</td>" + "</tr>"; } } table += "</table>"; // 核心邮件发送逻辑 const targetOption = "Increase Usage Priority (Ex: EBO)"; // 根据选项发送对应邮件 if (lastRowData[4] === targetOption) { MailApp.sendEmail({ to: "emailaddy1@test.com", subject: "Usage Priority - Mass Change Request Form Response", htmlBody: table, noReply: true }); } else { MailApp.sendEmail({ to: "emailaddy2@test.com", subject: "Mass Change Request Form Response", htmlBody: table, noReply: true }); } // 所有提交都发送给emailaddy3 MailApp.sendEmail({ to: "emailaddy3@test.com", subject: "All - Mass Change Request Form Response", htmlBody: table, noReply: true }); }
关键修改点
- 修复条件分支结构:将嵌套的
if改为else,确保两种情况都能触发对应邮件发送 - 调整emailaddy3的发送逻辑:移至条件分支外部,保证所有提交都会发送
- 优化数据获取方式:直接使用
getValues()返回的二维数组访问数据,避免逗号拆分导致的错误 - 封装时间戳处理逻辑:用函数复用代码,提升可读性
- 添加表格内边距:优化邮件表格的显示效果
内容的提问来源于stack exchange,提问作者RoniC
相关产品推荐
相关产品推荐

