Currently working on a Mail Merge project using Google Apps Script, I've encountered an issue with displaying inline images in the email body. After sending the email using GmailApp.sendEmail(), all inline images are shown as attachments instead of being displayed inline.
I believe that by converting the imgVars array to a JSON object similar to the example provided in the GAS documentation, it might be possible to display inline images:
MailApp.sendEmail(
"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c0b3a7eea1b0b0b3b3a3b2a9b0b480a7ada1a9aceea3afad">[email protected]</a>",
"Logos",
"",
{ htmlBody:
"inline Google Logo<img src='cid:googleLogo'> images! <br/> inline YouTube Logo <img src='cid:youTubeLogo'>",
inlineImages:
{ googleLogo: googleLogoBlob,
youTubeLogo: youtTubeLogoBlob
}
}
);
My goal is to convert an array structure like this:
var array = { item1, item2, item3 };
Into a JSON object structured like this:
var json = { item1Name: item1,
item2Name: item2,
item3Name: item3
};
In my Mail Merge script, this snippet focuses on handling inline images:
//---------------------------------------------------------------
// If there are inline images in the body of the email
// Find them and store them in an array, imgVars
//---------------------------------------------------------------
if(emailTemplate.search(/<\img/ != -1)) {
var inlineImages = {};
// Extract all images from the email body
var imgVars = emailTemplate.match(/<img[^>]+>/g);
// For each image, extract its respective title attribute
for (i in imgVars) {
var title = imgVars[i].match(/title="([^\"]+\")/);
if (title != null) {
title = title[1].substr(0, title[1].length-1);
for (j in attachments) {
if (attachments[j].getName() == title) {
inlineImages[title] = attachments[j].copyBlob();
attachments.splice(j,1);
}
}
var newImg = imgVars[i].replace(/src="[^\"]+\"/,"src=\"cid:"+title+"\"");
emailTemplate = emailTemplate.replace(imgVars[i],newImg);
}
}
}
objects = getRowsData(dataSheet, dataRange);
for (var i = 0; i < objects.length; ++i) {
var rowData = objects[i];
if(rowData.emailSent != "EMAIL_SENT") {
// Replace markers (for instance ${"First Name"}) with the
// corresponding value in a row object (for instance rowData.firstName).
var emailText = fillInTemplateFromObject(emailTemplate, rowData);
var emailSubject = fillInTemplateFromObject(selectedTemplate.getSubject(), rowData);
GmailApp.sendEmail(rowData.emailAddress, emailSubject, emailText,
{name: e.parameter.name,
attachments: attachments,
htmlBody: emailText,
cc: cc,
bcc: bcc,
inlineImages: inlineImages});