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

GmailApp重复发送邮件问题求助

解决Google Apps Script重复发送特定邮件问题

问题描述

我有一个可在多节点发送邮件的脚本,其中下面的两封邮件总是重复发送两次,但脚本内其他邮件均无此问题。我无法排查原因:代码未处于任何可能导致重复执行的循环中,且代码中设置了状态标记——发送邮件前会将状态设为"awaiting approval",按逻辑若代码重复执行会被首个IF条件拦截。

原代码

var ss = SpreadsheetApp.getActiveSheet();
var lastRow = ss.getLastRow();
var currentRow = ss.getCurrentCell().getRow(); //this is the row the user is in
  

function addEvent() { 
  var status = ss.getSheetValues(lastRow, 45, 1, 1).toString();
  if (status == "emails sent" || status == "awaiting approval") {return;}

  //if not approved yet ask for approval
  var approved = ss.getSheetValues(lastRow, 2, 1, 1);
  if (approved == "No" & status == "") { 
    
    ss.getRange(currentRow, 45).setValue("awaiting approval");
     
    var approvalBody = "stuff";

//THESE TWO EMAILS ARE GETTING SENT OUT TWICE EACH
    GmailApp.sendEmail(
      "admins@baltimoretherapycenter.com", 
      "New client approval needed.", 
      approvalBody
    );

    GmailApp.sendEmail(
      "raffi@xxxx.com", 
      "New client approval needed.", 
      approvalBody, 
      {from:'info@xxxx.com', name:"Approverizer"}
    );

    return;
  } //end request approval sequence

核心问题与解决方案

1. 状态判断与更新的行不匹配(最可能原因)

你用lastRow读取第45列的状态,但设置状态时用的是currentRow。如果用户操作的不是表格最后一行,就会出现判断的行和更新的行不一致:判断的是最后一行的状态(未被标记),但更新的是当前行,导致下次执行时依然能通过初始IF条件,重复触发邮件。

2. 逻辑运算符错误

第二个IF条件中使用了&(按位与),正确的逻辑与应该是&&。虽然某些场景下&能运行,但逻辑不严谨,可能导致条件意外成立。

3. 未强制刷新表格数据

SpreadsheetApp存在缓存机制,读取状态前未强制刷新,可能读取到旧的缓存状态,导致重复执行。

修正后的代码

var ss = SpreadsheetApp.getActiveSheet();

function addEvent() { 
  // 强制刷新表格数据,避免读取缓存
  SpreadsheetApp.flush();
  
  var currentRow = ss.getCurrentCell().getRow();
  // 统一使用当前行进行状态判断与更新
  var status = ss.getRange(currentRow, 45).getValue().toString().trim();
  
  // 严格判断状态,提前终止重复执行
  if (status === "emails sent" || status === "awaiting approval") {
    return;
  }

  var approved = ss.getRange(currentRow, 2).getValue().toString().trim();
  // 修正逻辑运算符为&&,确保条件严谨
  if (approved === "No" && status === "") { 
    // 更新当前行的状态
    ss.getRange(currentRow, 45).setValue("awaiting approval");
    // 再次刷新,确保状态立即写入表格
    SpreadsheetApp.flush();
     
    var approvalBody = "stuff";

    GmailApp.sendEmail(
      "admins@baltimoretherapycenter.com", 
      "New client approval needed.", 
      approvalBody
    );

    GmailApp.sendEmail(
      "raffi@xxxx.com", 
      "New client approval needed.", 
      approvalBody, 
      {from:'info@xxxx.com', name:"Approverizer"}
    );

    return;
  } 
}

额外排查点

  • 检查是否设置了重复触发的触发器(如时间驱动触发器),或用户是否不小心连续点击了触发按钮;
  • 确认脚本是否在多个执行环境(如不同用户、不同触发方式)下被同时调用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 18:05:38