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

Google Apps Script Sheets日期比对循环发校准邮件告警排查

故障原因

原脚本无法正常触发邮件发送,是以下明确的语法、数据结构使用错误导致的:

  • 代码首尾多余的三引号'''是无效语法,直接运行会直接抛出解析错误。
  • Google Apps Script中getRange().getValues()返回的是二维数组结构,每行数据存储在长度为1的子数组中,原代码直接访问数组索引未取内部值,还错误对数组元素调用仅Range对象支持的getValue()方法,直接触发运行时错误。
  • 实例化日期对象时遗漏new关键字,直接调用Date()只会返回时间字符串,不是可调用getTime()方法的标准Date对象。
  • 条件判断逻辑运算符优先级混乱,且未正确读取「已发运/已处理」列的标记值,导致判断结果永远为false,始终无法进入邮件发送分支。
  • 邮件正文拼接时错误把单个日期对象当数组访问,所有设备字段都未正确读取二维数组内的实际值,即使进入发送分支也会出现内容乱码。
  • 循环内重复读取固定不变的收件人邮箱单元格,不必要地消耗脚本运行配额。
修复后可直接运行的脚本

删除原脚本所有内容,替换为以下代码即可:

function checkCal(){
  // 绑定目标表格与工作表
  const ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1xKzfW5vX3-eDWKuKmc3R_xin4FMFKhDHaDAd7vdoaLE/edit#gid=0');
  const equipSheet = ss.getSheetByName("Equipment");
  const emailSheet = ss.getSheetByName("Emails");
  
  // 一次性读取所有需要的数据,减少接口调用
  const calibrationDateList = equipSheet.getRange("H2:H12").getValues();
  const vendList = equipSheet.getRange("C2:C12").getValues();
  const modelList = equipSheet.getRange("D2:D12").getValues();
  const cutoffDate = new Date(emailSheet.getRange("D1").getValue());
  const shippedList = equipSheet.getRange("I2:I12").getValues();
  const notesList = equipSheet.getRange("J2:J12").getValues();
  const snList = equipSheet.getRange("E2:E12").getValues();
  const locList = equipSheet.getRange("A2:A12").getValues();
  const emailAddress = emailSheet.getRange("B2").getValue();

  // 逐行校验校准日期
  for (let i = 0; i < calibrationDateList.length; i++){
    const calDate = new Date(calibrationDateList[i][0]);
    const isShipped = shippedList[i][0];
    // 跳过空日期、已标记完成校准/发运的行
    if (isNaN(calDate.getTime()) || isShipped) continue;
    // 校准日期早于等于截止日期时发送告警
    if (calDate.getTime() <= cutoffDate.getTime()){
      const vendor = vendList[i][0];
      const model = modelList[i][0];
      const sn = snList[i][0];
      const loc = locList[i][0];
      const note = notesList[i][0];
      const calDateStr = calDate.toLocaleDateString('zh-CN');
      
      const message = `设备校准到期提醒:${vendor} ${model},序列号:${sn},存放位置:${loc},校准到期日为${calDateStr}。请核对设备台账中的校准日期与序列号信息,及时安排校准。备注:${note || '无'}`;
      const subject = '设备校准告警';
      MailApp.sendEmail(emailAddress, subject, message);
    }
  }
}
使用注意事项
  • 运行前确认表格列与代码匹配:Equipment表A列为存放位置、C列为供应商、D列为设备型号、E列为序列号、H列为校准日期、I列为已处理标记(建议插入复选框,勾选后对应行不再触发告警)、J列为备注;Emails表B2为告警收件人邮箱、D1为告警截止日期。
  • 第一次运行脚本时,根据弹窗提示完成授权,允许脚本访问表格、发送邮件即可。
  • 如果需要定时自动运行,可在脚本编辑器的「触发器」菜单中添加定时触发规则,比如设置每天固定时间运行一次checkCal函数。

内容的提问来源于stack exchange,提问作者M.J.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 00:54:28