仅在填写前两列时发送电子邮件

时间:2018-03-15 19:23:35

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

我目前正在使用此脚本,以便在编辑最后一行时,它会发送一封电子邮件,其中包含该行前两列的内容。我的问题是,如果将信息输入到最后一行的任何列,则会发送一封空白电子邮件。我已经尝试了if语句的组合来获得我想要的结果,但最终结果是脚本正常工作,或者根本不工作。

// This function grabs the last row of a inventory sheet and sends the updated range to a specified recipient using a onEdit trigger
function sendEmails() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  // If edit is not made on "Iventory" sheet then function does not proceed
  if (sheet.getSheetName() != "Inventory") return;
  // Get last row of sheet
  var lastRow = sheet.getLastRow();
  // Get range of last row
  var lastCell = sheet.getRange(lastRow, 1, 1, 2);
  // Fetch values for each row in the Range.
  var data = lastCell.getValues();
  //empty string
  var message =""
  //Loop through each row and form CSV data
  for (var i = 0; i < data.length; i++) {
    var row = data[i];
    message = message + row[0] + "-" +row[1] + "\n";  
  }
  // Send one email with all the rows
  var subject = "Inventory update"; 
  MailApp.sendEmail("test@test.com", subject, message);
}

1 个答案:

答案 0 :(得分:1)

试试这个:

var send=true;
for (var i=0;i<data.length;i++) { 
    var row = data[i];
    message = message + row[0] + "-" +row[1] + "\n";  
  if(!row[0] || !row[1]){
    send=false;
    break;
  }
}
  // Send one email with all the rows
  var subject = "Inventory update"; 
if(send){
  MailApp.sendEmail("test@test.com", subject, message);
}