Google Appscripts - Do not send email if table is empty

47 views Asked by At

I have prepared a simple script which sends automatic emails triggered by event Time. I have found a barrier where script sending an empty table to person. Is there option that script wont send an email if table is empty?.

Here is a script that i use.


  function sendmail() {

  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Email2");
  
  var bodyEmail = "Email body"

  var totalRows = sheet.getLastRow();
  var totalCols = sheet.getLastColumn();

  var table = "<html><body><br><table border=1>"
  var colVal = "";

  for (var rowNo = 1; rowNo  <= totalRows; rowNo ++) {
    table = table + "<tr>"
    for (var colNo = 1; colNo <=totalCols; colNo++) {
      colVal = sheet.getRange(rowNo ,colNo).getDisplayValue();
      if(rowNo==1){
        table = table + "<th>" + colVal + "</th>";
      }
      else{
        table = table + "<td>" + colVal + "</td>";
      }
    }
    table = table + "</tr>"
    }

    bodyEmail=bodyEmail + table
    const currentMonth = Utilities.formatDate(new Date(), "GMT+4", "MMMM ");
      var today = new Date();
      var month = today.getMonth() + 1;
      var year = today.getFullYear();
      var emails = ["[email protected]","[email protected]"];
      for (var i = 0; i < emails.length; i++)

    GmailApp.sendEmail(emails[i],"Title of emial " + currentMonth + year + "","",{htmlBody:bodyEmail});

 
  }
  

Thank you in advance for your support!.

Email wont be sent if table is physically empty

1

There are 1 answers

2
Cooper On

How about:

if(!sheet.getRange(startRow, 1, sheet.getLastRow() - startRow + 1, sh.getLastColumn()).isBlank()) {
  //Send Email
}