Looking for google-apps-script Answers? Try Ask4KnowledgeBase
Looking for google-apps-script Keywords? Try Ask4Keywords

google-apps-script Sending HTML content in mail


Example

In the above example, if we want to send out HTML content as message in the email, then create a HTML file by going to File -> New -> HTML file

Now you can see a HTML file besides your gs file as follows :

enter image description here

Now, update the getMessage() method from above example as follows :

function getMessage(name, amount) {
  var htmlOutput = HtmlService.createHtmlOutputFromFile('Message'); // Message is the name of the HTML file
  
  var message = htmlOutput.getContent()
  message = message.replace("%name", name);
  message = message.replace("%amount", amount);
  
  return message;
}

The call to MailApp api needs to be changed as well

MailApp.sendEmail(recipientEmail, subject, message, {htmlBody : message});

So the whole code will be as follows :

function getDataSheet() {

  sheet = SpreadsheetApp.getActiveSheet();

  startRow = 2;  // First row of data to process
  numRows = 100;   // Number of rows to process
  startCol = 1;  //First column of data to process
  numCols = 15;    // Number of columns to process 
  
  var dataRange = sheet.getRange(startRow, startCol, numRows, numCols);

  // Fetch values for each row in the Range.
  var data = dataRange.getValues();  

  return data;  
}

function getMessage(name, amount) {
  var htmlOutput = HtmlService.createHtmlOutputFromFile('Message');
  
  var message = htmlOutput.getContent()
  message = message.replace("%name", name);
  message = message.replace("%amount", amount);
  
  return message;
}

function sendEmail() {
  
  var emailSent = "Yes";
  var reimbursed = "Yes";
  var emailCol = 5;
      
  var data = getDataSheet();
  
  for (var i = 0; i < data.length; i++) {
    
    var row = data[i];
    
    var isReimbursed = row[3];
    var isEmailSent = row[4];
    var name = row[0];
    var amount = row[2];
    
    if(isReimbursed == reimbursed && isEmailSent != emailSent) {
      
      var subject = "Reimbursement details";
      var message = getMessage(name, amount);
      
      var recipientEmail = row[1];
      
      MailApp.sendEmail(recipientEmail, subject, message, {htmlBody : message});
      
      sheet.getRange(startRow + i, emailCol).setValue(emailSent);
    }
  }
}