Google Script sendEmail触发器显示完成但未发送邮件问题
问题排查与修复方案
1. 修复未定义变量错误
代码中const queueSlots = sheete.getRange(rowr, 5).getValue();里的sheete未声明,需替换为已定义的dissheete:
const queueSlots = dissheete.getRange(rowr, 5).getValue();
该错误会直接中断函数执行,若执行日志显示“成功”,大概率是触发器测试未触达这段逻辑,或日志未捕获到错误。
2. 验证邮箱地址有效性
- 确认第7列(
emailAddress取值列)存在格式正确的邮箱地址,空值或无效格式会导致邮件无法发送且无报错提示。 - 可添加简单格式校验提前拦截:
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if (!emailRegex.test(emailAddress)) { console.error(`无效邮箱地址: ${emailAddress}`); return; }
3. 确保邮件核心变量完整
getLastNonEmptyCellValues函数若在列2、3、4中找不到非空值,会导致teacherName、meetingDetails、meetTime为undefined,拼接的邮件内容会出现异常,可能被邮箱服务商判定为垃圾邮件。添加校验逻辑:
if (nonEmptyValues.length < 3) { console.error("会议信息不完整,缺少教师姓名、会议详情或时间"); return; }
4. 检查邮件投递路径
- 优先查看测试邮箱的垃圾邮件/垃圾箱,GmailApp发送的邮件常被误判为垃圾邮件。
- 若使用Google Workspace账号,确认管理员未限制脚本的发件权限。
5. 触发器配置验证
- 必须使用可安装的onEdit触发器,简单触发器因权限限制无法调用GmailApp。
- 确认触发器事件类型为“编辑时”,触发条件匹配第6列的编辑操作。
修复后的完整代码
function sendEmail(e) { if (!e || !e.range) { console.error("Event object or range is missing."); return; } const dissheete = e.range.getSheet(); if (e.range.columnStart === 6 && e.range.rowStart > 1) { const rowr = e.range.getRow(); const emailAddress = dissheete.getRange(rowr, 7).getValue(); // 邮箱格式校验 const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if (!emailRegex.test(emailAddress)) { console.error(`无效邮箱地址: ${emailAddress}`); return; } const nonEmptyValues = getLastNonEmptyCellValues(dissheete, [2, 3, 4]); if (nonEmptyValues.length < 3) { console.error("会议信息不完整,缺少教师姓名、会议详情或时间"); return; } const teacherName = nonEmptyValues[0]; const meetingDetails = nonEmptyValues[1]; const meetTime = nonEmptyValues[2]; // 修复未定义变量问题 const queueSlots = dissheete.getRange(rowr, 5).getValue(); const queueEntryName = e.value; if (!queueEntryName) { console.error("队列姓名为空,无法发送邮件"); return; } const subject = "Academic Advising Schedule: Slot Confirmation"; const message = `Greetings, ${queueEntryName}!\n\n` + "You have been added to the meeting queue. Please take note of the meeting's details. \n\n" + `Meeting with: Mr/Ma'am ${teacherName}\n` + `Meeting Details: ${meetingDetails}\n` + `Meeting Time: ${meetTime}\n` + `Queue Slot: ${queueSlots}\n\n` + "Please keep a copy of this message, and take note of the time when you received this. In case someone replaces your name in the Queueing Sheet, please present this confirmation email to your adviser." + "Please make sure to attend the said schedule. Thank you!"; try { GmailApp.sendEmail(emailAddress, subject, message); console.log(`邮件已成功发送至: ${emailAddress}`); } catch (err) { console.error(`发送邮件失败: ${err.message}`); } } } function getLastNonEmptyCellValues(dissheete, columns) { const lastRow = dissheete.getLastRow(); const nonEmptyValues = []; columns.forEach(function(column) { for (let i = lastRow; i > 0; i--) { const cellValue = dissheete.getRange(i, column).getValue(); if (cellValue !== "") { nonEmptyValues.push(cellValue); break; } } }); return nonEmptyValues; }
内容的提问来源于stack exchange,提问作者meue1004
相关产品推荐
相关产品推荐

