从Google Apps发送电子邮件

时间:2016-06-19 16:41:29

标签: google-apps-script google-apps

我对Google Apps的自定义脚本(特别是Google Spreadsheets)感到困惑。

我从https://developers.google.com/apps-script/articles/sending_emails#section-2-improvements复制了课程(参见"第2部分:改进")但它不起作用:即使单元格已经包含&,脚本也会再次重新发送所有电子邮件#34; EMAIL_SENT" (我使用" NOTIFICATION_SENT"而不是这个。)

以下是自定义脚本的来源:

var NOTIFICATION_SENT = "NOTIFICATION_SENT";

function NotifyNewBooking() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var numRows = 47;   // Number of rows to process
  // Fetch the range of cells A2:N48
  var dataRange = sheet.getRange(startRow, 1, numRows, 17)
  // 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 = "natalya@berdyanskaya56.ru";
    var subject = "Строка № " + row + ": " + "новое бронирование";
    var message = "Уведомление о новом бронировании!" + "\n" + "\nДанные нового бронирования:" + "\n" + "\nЗаезд: " + row[0] + "\nВыезд: " + row[1] + "\nНомер: " + "«" + row[2] + "»" + "\nТип размещения: " + row[3] + "\nЦена за ночь: " + row[4] + " руб." + "\nВнесённый депозит: " + row[8] + " руб." + "\n" + "\nИмя и фамилия гостя: " + row[5] + "\nМобильный телефон: " + row[6] + "\nЭлектронная почта: " + row[7] + "\n" + "\nПримечание: " + row[11] + "\n" + "\n* Просмотреть список всех бронирований можно тут: " + "www.bitly.com/b56guests";  
    var notificationSent = row[17];     // The column where notification status is put
    if (notificationSent != NOTIFICATION_SENT) {  // Prevents sending duplicates
      MailApp.sendEmail(emailAddress, subject, message, {name: "Мини-гостиница Бердянская 56", replyTo: "ruslan@berdyanskaya56.ru"});
      sheet.getRange(startRow + i, 17).setValue(NOTIFICATION_SENT);
      // Make sure the cell is updated right away in case the script is interrupted
      SpreadsheetApp.flush();
    }
  }
}

此处的目标是仅在row[17]列中的单元格不包含NOTIFICATION_SENT时才发送电子邮件。请给我一些强有力的建议如何修复它。

提前非常感谢你!

1 个答案:

答案 0 :(得分:0)

问题出在这一行:<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table width="300" border="1" align="center" id="mainTable"> <tr> <td><input onkeyup="insertToArray(value)" size="1" maxlength="1" /></td> </tr> </table>

尝试通过记录值var notificationSent = row[17];Logger.log(row[17])来调试代码,然后在行[16]中的Logger.log(row[16])和行[16]中的undefined

为什么?因为Range。getValues返回一个二维数组,数组索引从0开始。

它也在documentation中指定。

  

请记住,当范围索引从1,1开始时,JavaScript数组将从[0] [0]索引。

因为你在for循环中初始化了 i到0 ,所以行正常。

NOTIFICATION_SENT

获取列时,应从索引中减去1。

for (var i = 0; i < data.length; ++i) { 
    var row = data[i]; 
    ....

因为如果你有17列,那么数组中的第一个值将从索引0开始直到16。