You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Apps Script条件分支报错:如何实现双条件触发不同邮件发送?

问题分析与代码修正

原代码的核心错误:

  • if/else语法混乱:if语句中return后多余的大括号导致逻辑错位,且else不能直接附带条件,需改用else if
  • 模板字符串未闭合:else分支的HTML模板字符串缺少结尾的反引号,引发语法报错
  • 变量误用:else分支发送邮件时调用了未定义的msg(实际定义的是msg1),且msg1未添加分号
  • 变量赋值重复:remarks和paticipateTicket都赋值为rData[0][1],属于列索引错误
  • HTML内容缺失:确认邮件的HTML中ticket type of后未插入ticketType变量,内容不完整

修正后的代码:

function sendMailEdit(e) {
  const rData = e.source.getActiveSheet().getRange(e.range.rowStart, 1, 1, 15).getValues();
  const participateTicket = rData[0][1]; // 修正拼写错误paticipate→participate
  const ticketType = rData[0][2];
  const ticketNumber = rData[0][14];
  const company = rData[0][3];
  const name = rData[0][4];
  const email = rData[0][5];
  const remarks = rData[0][10]; // 请根据实际表格列索引修改,原代码重复赋值了rData[0][1]

  // 先过滤非第17列的修改操作
  if (e.range.columnStart !== 17) return;

  if (e.value === "Yes") {
    const html = `<h2> Hello ${name} !</h2><p>Your purchase of a ${participateTicket} under ${company} is confirmed with ticket number ${ticketNumber}. </p><p>See you at the tournament at the details below.</p>
    <p>Your ticket number is ${ticketNumber} with a ticket type of ${ticketType} and you'll be participating under ${company} </p><p><img src="https://drive.google.com/uc?export=view&id=1nMiIfUgfFPYn4YOzXmEwJlaiNRPyOHsI" width="200px" height="300px"></p>`;
    const msg = `${name}, Your payment has been verified. Your ticket number is ${ticketNumber}. Participating under ${company}`;
    GmailApp.sendEmail(email, "2022 Charity Golf Tournament", msg, { htmlBody: html });
  } else if (e.value === "No") {
    const html = `<h2> Hello ${name} !</h2><p>Your purchase of a ${participateTicket} under ${company} has been paused and here’s why: </p> <p> ${remarks}</p>`;
    const msg1 = `${name}, Your payment has been paused. Below is the reason why: ${remarks}`;
    GmailApp.sendEmail(email, "2022 Charity Golf Tournament", msg1, { htmlBody: html });
  }
}

额外调整说明:

  • 修正了paticipate的拼写错误,改为标准的participate
  • 将所有var替换为const(变量无需重新赋值时更安全规范)
  • 统一用模板字符串拼接内容,提升可读性和维护性
  • 修正了img标签的length属性为正确的height
  • 请根据实际表格结构,调整remarks对应的列索引

内容的提问来源于stack exchange,提问作者Lyrien

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 19:18:20