我正在使用以下脚本从Google表格发送电子邮件提醒,但希望对其进行修改,以便在每行的单元格F中指定的日期发送电子邮件。
var EMAIL_SENT = "EMAIL_SENT";
function sendEmails2() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 999; // 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[0]; // First column
var subject = row[1]; // Second column
var message = row[2]; // Third column
var emailSent = row[3];
if (emailSent != EMAIL_SENT) { // Prevents sending duplicates
MailApp.sendEmail(emailAddress, subject, message);
sheet.getRange(startRow + i, 4).setValue(EMAIL_SENT);
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}
这就是我所拥有的,任何在那里添加日期的尝试都失败了。
我之前遇到过这个问题:Google Apps Script - Send Email based on date in cell但无法将其与我的脚本结合使用。
答案 0 :(得分:2)
that previous answer中提供的解决方案Serge为您提供了一个非常灵活的脚本,能够使用日期/时间的任何部分作为发送标准。
这是一种更简单,更不灵活的方法。假设:
这里的神奇之处在于比较日期。 JavaScript Date object是从1970年世界时开始经过的时间的数字表示。比较日期的平等是很困难的。但是,由于上面的假设,我们只关心 date ,这很有帮助。为了解决时区问题并消除小时,分钟等的影响,我们只使用相同的Date方法从我们想要比较的日期对象生成日期字符串。 toLocaleDateString()
方法会为我们调整时区。
结果脚本:
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 = 999; // 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[0]; // First column
var subject = row[1]; // Second column
var message = row[2]; // Third column
var emailSent = row[3];
var reminderDate = row[5].toLocaleDateString(); // date specified in cell F
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, 4).setValue(EMAIL_SENT);
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}