使用脚本触发自动电子邮件时出错

时间:2018-04-07 04:28:06

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

我正在使用谷歌电子表格,如下所示:

   A             B                    C             D
1 Name        e-mail              Identifer       Status
2 Alex       ax@gmail.com         ERT ER          A
3 Micke      miike477@gmail.com   Ejyu er w       
4 John       john7788@tri.com     Arb Ed          C

我在列D中有一个下拉列表(比如A,B& C),现在我希望每当值发生变化时(最初列D将为空)在D列中针对特定Name,而不是通过下面提到的发件人ID和内容在列B中提到的电子邮件ID的自动电子邮件触发器。

每当列D中的值发生变化时,电子邮件应该触发,除了空白,如果以前的值是“B”,现在它变为“C”而不是邮件应该触发。

Sender-example@gmail.com
CC-TEST1 @ gmail.com,TEST2 @ gmail.com

电子邮件正文:

嗨Alex(Should be picked from column A depending against which name e-mail trigger

这里有句话。 您的 ERT ER Should be pick from column C)的一些句子的状态为 A should be pick from column D)。

的问候,
例如
123456789

我正在尝试使用下面提到的脚本:

function onEdit(event){
    if(event.range.getColumn() == 4){ //A -> 1, B -> 2, etc
        function sendMyEmail(line){
    var sendTo = spreadsheet.getRange(row, 2).getValue();
    var cc     = 'test1@gmail.com'+","+'test2@gmail.com';
    var subject = "What is the: "+ spreadsheet.getRange(row, 3).getValue();
    var content = "Hi "+spreadsheet.getRange(row, 1).getValue();+","

                 +"what is the vlaue "+spreadsheet.getRange(row, 3).getValue();+ "with the status"+spreadsheet.getRange(row, 4).getValue();+ "."
    MailApp.sendEmail(sendTo,
        cc,
        subject,
        content);
}
    }
}

1 个答案:

答案 0 :(得分:2)

你有两个主要问题。

  1. Simple triggers cannot access services that require authorization(例如MailApp)。

  2. 您对MailApp.sendEmail()的使用不正确,因为您已将cc传递到应传递主题或replyTo地址(docs)的位置。参数顺序很重要。

  3. 要解决简单触发器的问题,您需要做的就是install a trigger manually在编辑时调用您的函数。

    enter image description here

    以下代码中解决了所有其他问题。

    function sendEmailToUser(event){
      var eventRange = event.range;
      var sheet = eventRange.getSheet();
      var sheetName = sheet.getName();
      var column = eventRange.getColumn();
      if (sheetName == "Sheet1" && column == 4){ // Make sure the edited column is in the correct sheet, otherwise editing Column D in Sheet3 might trigger this
        var row = eventRange.getRow(); // You need to know which row so you can send the email to the correct person
        var rowValues = sheet.getRange(row, 1, 1, 4).getValues();
        var name = rowValues[0][0];
        var sendTo = rowValues[0][1];
        var identifier = rowValues[0][2];
        var status = rowValues[0][3];
        if (status != "") { // Don't send the email if the status is blank
          var cc = "test1@example.com, test2@example.com";
          var subject = "What is the: " + identifier;
          var content = "Hi " + name + "\nWhat is the value " + identifier + " with the status " + status + "?";
          MailApp.sendEmail(sendTo, subject, content, {
            cc: cc
          });
        }
      }
    }