用于在每次单元格旁边的单元格更新时向其中的特定单元格发送电子邮件的脚本

时间:2017-02-14 16:49:07

标签: google-sheets

我希望在我尝试做标题所说的之前,已经有人问过这个问题。

在这个特定的例子中,我在A栏上获得了电子邮件列表,我希望该电子邮件地址能够在其旁边的单元格获得更新时收到通知"是"

到目前为止,我得到了这个:

function Initialize() {

  var triggers = ScriptApp.getProjectTriggers();

  for(var i in triggers) {
    ScriptApp.deleteTrigger(triggers[i]);
  }

  ScriptApp.newTrigger("sendNotification")
  .forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
  .onEdit()
  .create();

};


/**
 * 
 */


function sendNotification(e) {


  if("B2" == e.range.getA1Notation() ) {

    if(e.value == "Yes") {



      var recipients = "IDK what to put in here";
      var subject = "There's an update to your request";
      var body = "We resolved your issue!";


      MailApp.sendEmail(recipients, subject, body);
    }
  }
}

1 个答案:

答案 0 :(得分:0)

我已经用注释编辑了代码来解释我改变了什么,你是在正确的轨道上。 OnEditTriggers发送电子邮件通常不赞成,通常不是一个好习惯。但是,在您的情况下,您仍然可以控制何时发送电子邮件,因此只需在每个编辑单独发送电子邮件时进行改进。

仅供参考你不需要初始化()来设置手动触发器,你可以手动设置它:https://developers.google.com/apps-script/guides/triggers/installable#managing_triggers_manually

 function Initialize() {
      var triggers = ScriptApp.getProjectTriggers();
      // The below code would delete all the triggers in your project not just the one you setup through this code.  
      for(var i in triggers) {
        ScriptApp.deleteTrigger(triggers[i]);
      }
      ScriptApp.newTrigger("sendNotification")
       .forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
       .onEdit()
       .create();
      };

   function sendNotification(e) {
      //if("B2" == e.range.getA1Notation() ) {
      //This will only check is the range is B2 cell, if you want to check for  column B. use getColumn
      if(e.range.getColumn() == 2){
        if(e.value == "Yes") {   
          //var recipients = "xxx@gmail.com"; //Email Address of the indented Recipents 
          // In your case email would be the value in cell A2 or cell in Column A corresponding to the one edited in Col B
          // you can get that value like so
          var recipients = e.source.getActiveSheet().getRange(e.range.getRow(),1).getValue()
          Logger.log(recipients)
          var subject = "There's an update to your request";
          var body = "We resolved your issue!";
          MailApp.sendEmail(recipients, subject, body);
        }
      }
    }

新功能:

e.range.getColumn()/ getRow()以获取特定的列或行。这样你就可以使用数字而不是字符串。与字符串相比,使用算术易于操作数字。

e.source.getActiveSheet()为您提供发生更改的工作表对象。您可以使用e.source.getActiveSheet()。getName()来获取工作表的名称,并使用它来确保仅在特定工作表上进行编辑时触发电子邮件。