如何在代码中编辑循环以发送一封包含所有数据的电子邮件?

时间:2019-10-23 17:31:28

标签: google-apps-script google-sheets

我的代码检查Google表格上是否有今天日期在特定列中的行。然后,通过电子邮件发送这些行中的某些单元格。我的目标是每天通过一封电子邮件接收所有符合该条件的行。

照原样,如果我有3条符合条件的行,我将收到3封电子邮件。第一封电子邮件有一条记录,第二封电子邮件有2条记录,第三封电子邮件有所有3条记录。

我确定这是一个简单的解决方法,但是我不确定如何编辑循环。

  var datasheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 1"); 
  var numRows = datasheet.getLastRow()-1
  var data = datasheet.getRange(2, 1, numRows, datasheet.getLastColumn()).getValues();
  var today = new Date().toLocaleDateString()
  var result = "";
  for (var i = 0; i < data.length; i++) { 
    var row = data[i];
    var enddate = new Date(row[14]).toLocaleDateString();
    if(enddate == today) { 
      result = result + row[8] + "   Dates: " + row [24] + " - "+ row[25] + '\n'
    }    
    if (result != "") {
      var body = "List of records ending today: " + '\n\n' 
      + result + ' \n' 
      GmailApp.sendEmail("user@domain.com","Daily ending today email", body, {
           from: 'do-not-reply@domain.com',}); 
    }
  } 
}

1 个答案:

答案 0 :(得分:2)

只需将电子邮件发送语句放在for循环之外:

      var datasheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 1"); 
      var numRows = datasheet.getLastRow()-1
      var data = datasheet.getRange(2, 1, numRows, datasheet.getLastColumn()).getValues();
      var today = new Date().toLocaleDateString()
      var result = "";
      for (var i = 0; i < data.length; i++) { 
        var row = data[i];
        var enddate = new Date(row[14]).toLocaleDateString();
        if(enddate == today) { 
          result = result + row[8] + "   Dates: " + row [24] + " - "+ row[25] + '\n'
        }    
      } 
      if (result != "") {
          var body = "List of records ending today: " + '\n\n' 
          + result + ' \n' 
          GmailApp.sendEmail("user@domain.com","Daily ending today email", body, {
               from: 'do-not-reply@domain.com',}); 
        }
    }