发送具有通过基于时间的触发器运行的功能的电子邮件

时间:2018-09-17 14:37:08

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

目标:在日期==今天自动触发脚本发送电子邮件

问题:手动运行时脚本可以工作,但是当使用“当前项目的触发器” 时,我会收到:

  • 没有错误消息
  • 没有电子邮件
  • 未使用“ EMAIL_SENT”填充工作表

脚本:

// Send email reminder to the team
var EMAIL_SENT = "EMAIL_SENT";
function sendEmails3() {
  var today = new Date().toLocaleDateString();  // Today's date, without time

  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var numRows = sheet.getLastRow()-1 // Get last row, -1 because your startrow is 2;   // Number of rows to process
  // Fetch the range of cells A2:B999
  var dataRange = sheet.getRange(startRow, 1, numRows, 999)
  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
  for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    var emailAddress = row[8];  // First column
    var subject = row[9];     // Second column
    var message = row[10];    // Third column
    var emailSent = row[11];
    //var reminderDate = row[6].toLocaleDateString();  // date specified in cell G
    var cellValue, reminderDate; //Define variables at top of function

    cellValue = row[6]; // date specified in cell C
    if (!cellValue) {continue;} //If there is no cell value continue looping

    if (typeof cellValue === 'object') {
      reminderDate = cellValue.toLocaleDateString();
    } else {
      cellValue = new Date(cellValue);//Convert date as string to object
      reminderDate = cellValue.toLocaleDateString();
    }

    if (reminderDate != today)      // Skip this reminder if not for today
      continue; 

    if (emailSent != EMAIL_SENT) {  // Prevents sending duplicates
      MailApp.sendEmail(emailAddress,subject,message);
      sheet.getRange(startRow + i, 12).setValue(EMAIL_SENT);
      // Make sure the cell is updated right away in case the script is interrupted
      SpreadsheetApp.flush();     
    }
  }
}

我提到了以下现有问答:

  1. Send reminder emails based on date,但是在使用“当前项目的触发器” 运行时,返回了错误“ TypeError:在对象中找不到函数toLocaleDateString。”。手动运行时效果很好。
  2. How do you send reminder date based on cell date in Google Sheets?,建议中断var reminderDate = row[2].toLocaleDateString();,但结果如上所述:通过触发器运行时什么也没有发生。

0 个答案:

没有答案