如何使用MailApp.SendEmail跳过空白单元格?

时间:2017-03-31 17:23:14

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

我一直在使用Google表单向工作簿收集信息,然后使用该信息将自定义电子邮件发送回发件人。我是编码的小伙子,但我已经设法凑齐了足够完成这项任务。我的问题是,当它涉及一个空白的电子邮件单元格时,它会停止。我试图让它跳过一个循环,没有成功。任何帮助,将不胜感激。这是我没有循环使用的程序。

maxima = {}
my_dict = { 111: [50, 2, 34], 122: [50 , 4, 45], 133: [40, 1, 12], 144: [20, 5, 7]}

for key in my_dict:
    maxima[key] = max(my_dict[key])

max_keys = [key for key in maxima if maxima[key] == max(maxima.values())]
print max_keys

1 个答案:

答案 0 :(得分:1)

您可以使用string.match()函数来确定单元格是否为空。由于您正在寻找电子邮件地址,因此您可以查看该单元格是否有“@”符号。如果不排除单元格并继续下一个单元格,如下所示:

if (emailAddress.match('@')  === null){
 continue;  // skip this iteration of the loop and go to the next one
}

您的最终代码如下:

var EMAIL_SENT = "EMAIL_SENT";
function sendEmails2() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var numRows = 2000;   // Number of rows to process
  // Fetch the range of cells A2:B2001
  var dataRange = sheet.getRange(startRow, 1, numRows, 2001)
  // 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
    if (emailAddress.match('@')  === null){
       continue;  // skip this iteration of the loop and go to the next one
    };  
    var message = row[1];       // Second column
    var emailSent = row[2];     // Third column
    if (emailSent != EMAIL_SENT) {  // Prevents sending duplicates
      var subject = "Bounce Reply";  
      MailApp.sendEmail(emailAddress, subject, message);
      sheet.getRange(startRow + i, 3).setValue(EMAIL_SENT);
      // Make sure the cell is updated right away in case the script is interrupted
      SpreadsheetApp.flush();
      }
    }
  }

修改

要检查某些东西是否为空,你可以试试这样的东西。

if (message.match(/[a-zA-Z0-9_]/) === null) {  //" /[a-zA-Z0-9_]/ " is regex  to match any and every alphanumeric letter including underscore
 continue; // skip this iteration of the loop and go to the next one
}

您可以找到有关功能match and regex here.

的更多详细信息

希望有所帮助!