Google Apps脚本发送带有触发器的自动电子邮件(不重复)

时间:2018-12-17 11:14:01

标签: google-apps-script google-sheets triggers

我正在尝试使用脚本和触发器通过Google表格设置自动电子邮件。

如何定义仅新添加到电子表格的内容才能触发电子邮件?电子表格会不断添加到。

function sendloggeremails() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var lr = ss.getLastRow()

  for (var i = 72; i <= lr; i++) {
    var currentEmail = ss.getRange(i, 7).getValue();
    var currentClassTitle = ss.getRange(i, 3).getValue();

    MailApp.sendEmail(currentEmail, "complaint: customer number " + currentClassTitle ,  "Please check through the log as you have a new assigned to you");
  }
}

var i = 72显然是因为这是最后一行,所以我不需要手动不断更改它。添加了触发器,但此刻我仍然需要进入代码来更改var i

有没有机会有人可以帮助您?

1 个答案:

答案 0 :(得分:0)

仅循环发送电子邮件一次

您可以使用类似这样的东西。首先,您需要在“已发送”列中添加一些内容,以便旧行不会重新发送其电子邮件,并且您仍会保留过去的电子邮件记录。我建议将字符串“ SENT”放入。但是测试只是问一个问题:该列为空,所以任何东西都可以工作。

很显然,我还没有看到您的电子表格,所以我不知道将sendColumn放在哪里,因此您可以将var sendColumn = 75更改为所需的任何值,并且它使用的所有其他位置都将相应地更改。

function sendloggeremails() {
  var ss=SpreadsheetApp.getActiveSpreadsheet();
  var sh=ss.getActiveSheet();//You should probably change this to getSheetByName() and then put in the correct name of the sheet
  var sentColumn=75;//If this column is not empty then don't send emails.  If you send any email then also put "SENT" into this column so you wont resend it next time you run the loop.
  sh.getRange(1,sentColumn).setValue("Sent");//I'm assuming a header row and I'm putting a Header Title there you can pick any open column you want
  var rg=sh.getDataRange();//This gets all of the sheets data into one one range
  var vA=rg.getValues();//This gets all of the values in above range in a two dimension object we often refer to as a two dimensional array.
  //If you have header row you can start at i=1
  for(var i=1;i<vA.length; i++) {//This will loop over all of the rows on the sheet.
    if(!vA[i][sentColumn-1]){//Heres the test to see if theres something in sentColumn.  If sentColumn is empty meaning truthy is false then it send the email
      var currentEmail=vA[i][6];//this replaces the getValue from column7 *1
      var currentClassTitle=vA[i][2];//this replaces the getValue from column3 *1
      MailApp.sendEmail(currentEmail, "complaint: customer number " + currentClassTitle ,  "Please check through the log as you have a new assigned to you");
      sh.getRange(i+1,sentColumn).setValue("SENT");//After sending email we put something.  In this case "SENT" into the sentColumn so that next through the loop we won send another email because its truthy will be true.
    }
  }
}
//*1 Array indices are 1 less that column numbers because arrays start counting from zero.

如果您愿意,我们还可以在发送行时将其删除。您要做的就是跟踪每次循环运行后删除了多少行,并说一个像var n = 0这样的变量开始,然后要删除的行号将为i-n + 1。在删除后,您将n加1。

您可以使用此功能设置触发器。

function setupEmailTrigger() {  
  if(ScriptApp.getProjectTriggers().indexOf('sendloggeremails')==-1){
    ScriptApp.newTrigger('sendloggeremails').timeBased().everyDays(1).atHour(17).create();
  }
}

它检查触发器是否已经存在,以及触发器是否已经存在。