在新表单提交条目上发送重复的电子邮件

时间:2017-06-17 18:10:14

标签: google-apps-script google-sheets

我有以下脚本,根据表单提交中的一个字段向相应的人发送电子邮件。它工作正常,但每次提交新条目时都会发送多封电子邮件,我不确定原因。有人能告诉我我的代码中有什么问题需要解决吗?

function sendEmails() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var numRows = 2;   // Number of rows to process
  // Fetch the range of cells A2:B3
  var dataRange = sheet.getRange(startRow, 1, numRows, 3)
  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
  var email1 = "A@A.com";
  var email2 = "B@B.com";
  for (i in data) {
    var row = data[i];
    var emailAddress = row[0];  // First column
    var message = row[1];       // Second column
    var subject = "Sending emails from a Spreadsheet";
  if (message = "cat") {
    MailApp.sendEmail(email1, subject, message);
  if (message = "dog") {
    MailApp.sendEmail(email2, subject, message);
  }
   }
    }
      }

2 个答案:

答案 0 :(得分:2)

这些行:

if (message = "cat") {
  MailApp.sendEmail(email1, subject, message);
if (message = "dog") {
  MailApp.sendEmail(email2, subject, message);
}

应该是:

var email;//Create a new variable

if (message == "cat") {
  email = email1;
} else if (message == "dog") {
  email = email2;
}

MailApp.sendEmail(email, subject, message);

答案 1 :(得分:1)

我非常确定表单提交会在最后一行结束,并且不需要遍历行。这假设您没有掺杂带有数组公式等的表单提交表。

function sendEmails() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var row = sheet.getLastRow();
  var dataRange = sheet.getRange(row, 1, 1, sheet.getLastColumn());
  var data = dataRange.getValues()[0];

  var email1 = "A@A.com";
  var email2 = "B@B.com";

  var emailAddress = data[0];  // First column
  var message = data[1];       // Second column
  var subject = "Sending emails from a Spreadsheet";

  if (message == "cat") {
    MailApp.sendEmail(email1, subject, message);
    };
  if (message == "dog") {
    MailApp.sendEmail(email2, subject, message);
    };
   }

最后一部分可能会通过Sandy的建议或转换>案例

进行改进