如何使此功能发送一次电子邮件并将实体更改为“已选中”

时间:2019-12-04 14:26:09

标签: javascript google-apps-script web-applications

嗨,我有一个功能,如果实体包含“ 126d”,该功能将发送电子邮件。它当前在每次更改时运行,因此每次有“ 126d”的实体且每次更改时都会向我发送电子邮件。

很显然,我只想接收一次电子邮件,所以我的解决方案是拥有一个“状态”列,其中当一个实体包含“ 126d”并且一封电子邮件已发送一次时,它将更改将同一行“选中”。不幸的是,到目前为止,我一直未能成功。感谢您的帮助,谢谢!

function CheckMail() {
  var mailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("List").getRange("A1:A500"); 
  var data = mailRange.getValues(); 
  var dataLength = data.length;
      for(var i=0;i<dataLength;i++){
        if(data[i][0] == "126d" || data[i][0] == "126D") {
          var range = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("List").getRange("B1:B500"); 
          var name = range.getValues();
          var emailAddress = "email@gmail.com"
          var subject = "New parcel from " + name[i][0];
          var message = "Row " + (i+1) + " www.spreadsheet.com";
          MailApp.sendEmail(emailAddress, subject, message);
        }
      }
}

更新: 我尝试了@James Ds解决方案,但奇怪的是,尽管将状态设置为“已检查”,它仍然会发送一封新电子邮件。

function CheckMail() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("List")
  var data = ss.getRange("A1:D500").getValues(); // Read all data in A1:D500

  for(var i=0;i<data.length;i++){ // Loop through all data
    if(data[i][0] == "126d" || data[i][0] == "126D" && data[i][3] != "checked") { // Check that A[i] is 126d and D[i] is not checked ([3] means col 3)    
      var emailAddress = "email@gmail.com" 
      var subject = "New parcel from " + data[i][1]; // get the subject from col B
      var message = "Row " + (i+1) + " www.spreadsheet.com"; // Message with row number
      MailApp.sendEmail(emailAddress, subject, message); // Send the mail
      ss.getRange(i + 1, 3).setValue("checked") // Set the 3rd column (D) to checked if the mail was sent
    }
  }
}

1 个答案:

答案 0 :(得分:1)

您没有尝试在任何地方设置值“ checked”吗?

此代码应该对范围和列进行一些较小的修改即可满足您的需求

function CheckMail() {
 var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("List")
 var data = ss.getRange("A1:D500").getValues(); // Read all data in A1:D500

 for(var i=0;i<data.length;i++){ // Loop through all data
     if((data[i][0] == "126d" || data[i][0] == "126D") && data[i][2] != "checked") { // Check that A[i] is 126d and D[i] is not checked ([C] means col C)    
  var emailAddress = "mail@gmail.com" 
  var subject = "New parcel from " + data[i][1]; // get the subject from col B
  var message = "Row " + (i+1) + " www.spreadsheet.com"; // Message with row number
  MailApp.sendEmail(emailAddress, subject, message); // Send the mail
  ss.getRange(i + 1, 3).setValue("checked") // Set the 3rd column (D) to checked if the mail was sent
  }
 }
}