Neill
Neill

Reputation: 452

GmailApp - Inline images are attached, and not inline - send email with images in body

I created a Google Script to email several charts as images. When using MailApp it works, and the images are in the body of the email. When using GmailApp, the images are as attachments and not in the email body. I want to use GmailApp because I can use an alias, and because I figured out how to make the email send to a list of people. How do I make a change so that the GmailApp function sends the email with the charts contained in the body? Here is a link to a sample spreadsheet, and here is the code:

function SRpt2() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sstotalsheets = ss.getNumSheets();
  var clientCode =  ss.getSheetByName("Info").getRange("C4").getDisplayValue();
  var progmgr = ss.getSheetByName("Info").getRange("D11").getDisplayValue();
  var sheetcount = 0;
  var token = ScriptApp.getOAuthToken();
  var sheets = ss.getSheets(); 
  var blobs = [];
  var subject = "Daily " + clientCode +" Digest"; 
  var body = "Your daily update";
  var recips = progmgr + ", [email protected]";
  var emailImages={};
  var emailBody="Charts<br>";

  for (var i = 5; i < sheets.length ; i++ ) {
    var sheet = sheets[i];
    var charts = sheet.getCharts(); 

    if(charts.length > 0) {
      var template = HtmlService.createTemplateFromFile("reportTemplate");
      template.date = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "MM-dd-yyyy");
      blobs[i] = charts[0].getBlob().getAs('image/png').setName("areaBlob");
      emailBody= emailBody + "<img src='cid:chart"+i+"'><br>";
      emailImages["chart"+i]= blobs[i];
    }
  }

  var me = Session.getActiveUser().getEmail();
  var aliases = GmailApp.getAliases();
  if (aliases.length > 0) {
    GmailApp.sendEmail(recips, subject, emailBody, {'from': aliases[0],inlineImages:emailImages});
  }

  MailApp.sendEmail({
    to: recips,
    subject: subject,
    htmlBody: emailBody,
    inlineImages:emailImages});
}

And here is the html it refers to:

<html>
  <h1>Daily Update <?= date ?></h1>
  <p>
    <img src="cid:chart" />
  </p>
</html>

The incorrectly formatted email body just says the actual html source code (I can't figure out how to paste it into the stackoverflow without it actually treating it as html).

Upvotes: 1

Views: 1313

Answers (1)

Alan Wells
Alan Wells

Reputation: 31310

Add the HTML to the options object. And make the body parameter and empty string.

var options;

options = {};//Assign an empty object to the variable options

//{'from': aliases[0],inlineImages:emailImages}
options.from = aliases[0];
options.inlineImages = emailImages;
options.htmlBody = emailBody;

if (aliases.length > 0) {
  GmailApp.sendEmail(recips, subject, "", options);//Leave body an empty string
}

Upvotes: 1

Related Questions