需要帮助迭代Google工作表中的列并根据单元格中的每个值发送电子邮件

时间:2017-03-24 18:09:43

标签: google-apps-script google-sheets

我猜这是一件很简单的事,但我不知道该怎么办。我有一个谷歌脚本,我想每天运行,单独检查谷歌工作表中一列内的单元格值,如果值低于某个阈值,则发送一封电子邮件。

到目前为止我所拥有的是

function sendEmail() {
  var data = SpreadsheetApp.getActiveSheet().getRange('E2').getValue();
  if (data < 300){
     var emailAddress = "emailaddress@email.com";
     var message = "test body";
     var subject = "test subject";
     MailApp.sendEmail(emailAddress, subject, message);
  }
}

修改

这是我现在的位置。除了从单元格中提取电子邮件外,它的工作原理。

function sendEmail() {

    function letThemKnow(num) { //This creates a function named letThemKnow which is passed the variable num from the if/else statements
        var emailAddress = email[i]; //Sets the variable to the email address of
        var message = "Greetings! This is an automated message to let you know your license for " + software[i] + " expires in " + num + " days.";
        var subject = "Impending expiration of " + software[i];
        MailApp.sendEmail(emailAddress, subject, message);
    }
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sh = ss.getActiveSheet();
    var lastRow = sh.getLastRow();
    var data = sh.getRange(2, 5, lastRow, 1).getValues();
    var software = sh.getRange(2, 1, lastRow, 1).getValues();
    var email = sh.getRange(2, 7, lastRow, 1).getValues();
    for (i = 0; i <= email.length; i++) {
        for (i = 0; i <= software.length; i++) {
            for (i = 0; i <= data.length; i++) {
                var num = parseInt(data[i]);
                if (num == 30) {
                    letThemKnow(num)
                } else if (num == 14) {
                    letThemKnow(num)
                } else if (num <= 7) {
                    letThemKnow(num)
                }
            }

        } // 
    }
} // 

1 个答案:

答案 0 :(得分:0)

你的for循环从'0'开始,到'0'结束。试试这个:

function sendEmail() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh = ss.getActiveSheet();
  var lastRow = sh.getLastRow();
  var data = sh.getRange(2,5,lastRow,1).getValues();
  for (i=0;i <= data.length;i++){
     var num = parseInt(data[i]);
     if (num < 300) {
       var emailAddress = "email@email.com";
       var message = "test body";
       var subject = "test subject";
       MailApp.sendEmail({
           name: "Your Name",
           to: emailAddress,
           subject: subject,
           htmlBody: message
       });
     }
   }
}

如果电子邮件每次都相同,您应该在循环之外定义这些变量。