Google Apps脚本 - 根据单元格中的数据发送电子邮件

时间:2014-02-13 01:23:22

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

所以我正在设置一个提醒电子邮件,根据单元格中的日期自动发送。有点像这样:Google Apps Script - Send Email based on date in cell 这是我的示例工作簿:https://docs.google.com/spreadsheet/ccc?key=0AiHAV8ZZ5nexdDJqODhmamhldjN1ZTRKc09iZXNBZ3c#gid=0

这是我的代码:

function sendEmail() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2;  // First row of data to process
var numRows = sheet.getLastRow()-1;   // Number of rows to process
// Fetch the range of cells A2:B3
var dataRange = sheet.getRange(startRow, 1, numRows, sheet.getLastColumn());
// Fetch values for each row in the Range.
var data = dataRange.getValues();
//Logger.log(data)

for (i in data) {
var row = data[i];
var date = new Date();
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
//Logger.log(date);
var sheetDate = new Date(row[2]);
//Logger.log(sheetDate);
var Sdate = Utilities.formatDate(date,'GMT+0200','yyyy:MM:dd')
var SsheetDate = Utilities.formatDate(sheetDate,'GMT+0200', 'yyyy:MM:dd')
 Logger.log(Sdate+' =? '+SsheetDate)
    if (Sdate == SsheetDate){
      var emailAddress = row[0];  // First column
      var message = row[1];       // Second column
      var subject = "It's time to practice!" +message;
      MailApp.sendEmail(emailAddress, subject, message);
      //Logger.log('SENT :'+emailAddress+'  '+subject+'  '+message)
        }    
 }
}

但我不确定它是否有效,是否会自动发送电子邮件?显然,我知道的剧本很少。

1 个答案:

答案 0 :(得分:0)

此处共享的现有代码中只有1个错误,即使其无法正常工作:

  

var sheetDate = new Date(row [2]);

您的数组中只有2个索引,因此应该是:

  

var sheetDate = new Date(row [1]);

此外,因为您正在使用Utilities.formatDate yyyy:MM:dd格式,所以您不需要设置小时分和秒,因为Utilities.formatDate返回的字符串没有时间组件。此外,您不需要创建sheetDate或date,它们都可以构造为Utilities.formatDate中的第一个参数(参见下文)。关于这个主题的另一件事是,因为您的日期值被格式化为电子表格中的日期,它们将作为日期对象返回到您的脚本,所以实际上,没有必要调用新的日期(行[1]) ..但它没有伤害任何东西。

function sendEmail() {
  try{
    var sheet = SpreadsheetApp.getActiveSheet();
    var startRow = 2;  // First row of data to process
    var numRows = sheet.getLastRow()-1;   // Number of rows to process
    // Fetch the range of cells A2:B3
    var dataRange = sheet.getRange(startRow, 1, numRows, sheet.getLastColumn());
    // Fetch values for each row in the Range.
    var data = dataRange.getValues();

    for (i in data) {
      var row = data[i];
      //Logger.log(sheetDate);
      var Sdate = Utilities.formatDate(new Date(),'GMT-0500','yyyy:MM:dd')
      var SsheetDate = Utilities.formatDate(new Date(row[1]),'GMT+0200', 'yyyy:MM:dd')
      Logger.log(Sdate+' =? '+SsheetDate)
      if (Sdate == SsheetDate){
          var emailAddress = row[0];  // First column
          var message = row[1];       // Second column
          var subject = "It's time to practice!" +message;
          MailApp.sendEmail(emailAddress, subject, message);
          //Logger.log('SENT :'+emailAddress+'  '+subject+'  '+message)
       }    
     }
   }catch(err){
     Logger.log(err.lineNumber + ' - ' + err);
   }
}