如何从我的表单的最后一行发送电子邮件

时间:2018-04-12 11:56:02

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

我对编码很陌生,我无法弄清楚我做错了什么。我需要从表单中的最后一个条目发送一封电子邮件。因此,当学生提交他们的预测试时,他们会收到一封包含预测试结果的电子邮件。 这就是我的代码:

function sendEmails() {
      var sheet = SpreadsheetApp.getActiveSheet();
      var startRow = 3;  // First row of data to process
      var numRows = 1;   // Number of rows to process
      // Fetch the range of cells A2:B3
      var dataRange = sheet.getRange(startRow, 3, numRows, 1)
      // Fetch values for each row in the Range.
      var data = dataRange.getValues();
      for (i in data) {
      var row = data[i];
      var emailAddress = row[1];  // Second column
      var message = row[2];       // Third column
      var subject = "Résultat de formatif";

      // This logs the value in the very last cell of this sheet
     var lastRow = sheet.getLastRow();
     var lastColumn = sheet.getLastColumn();
     var lastCell = sheet.getRange(lastRow, lastColumn);
     Logger.log(lastCell.getValue());


    MailApp.sendEmail(emailAddress, subject, message);
  }
}

2 个答案:

答案 0 :(得分:0)

我是这样做的:

  • 在工作表中添加单独的“STATUS”列
  • 在您的电子邮件发送功能中迭代行,仅对“STATUS”为空白的行执行
  • 成功发送电子邮件后,将某些内容添加到“状态”列

答案 1 :(得分:0)

请查看event object documentation

您可以install a "trigger"在每个表单提交时自动运行脚本。由于每次提交都会触发此操作,因此您无需担心尝试查找最后一行或是否已发送电子邮件。

function sendEmails(formResponse) {
  var answers = formResponse.values;
  var emailAddress = answers[1];  // Second column
  var message = answers[2];       // Third column
  var subject = "Résultat de formatif";

  // This logs the value in the very last cell of this sheet
  var range = formResponse.range;
  var row = range.getRow();
  var column = range.getLastColumn();

  try {
    MailApp.sendEmail(emailAddress, subject, message);
  } catch (e) {
    console.error("Did not send email to " + emailAddress + ". See error: " + e);
    range.getSheet().getRange(row, column+1).setValue("EMAIL NOT SENT");
    return;
  } 
  range.getSheet().getRange(row, column+1).setValue("EMAIL SENT");
}

enter image description here