我正在修改 Google Apps 脚本中的邮件合并项目。我面临的问题是如何使电子邮件正文显示内联图像。目前,在调用 GmailApp.sendEmail() 后,原始电子邮件模板中存在的所有内联图像都显示为附件。
我的猜测是,如果我找到某种方法将 imgVars 数组转换为这样的 JSON 对象(取自GAS 文档中的示例),则可以显示内联图像:
MailApp.sendEmail(
"sg.appsscript@gmail.com",
"Logos",
"",
{ htmlBody:
"inline Google Logo<img src='cid:googleLogo'> images! <br/> inline YouTube Logo <img src='cid:youTubeLogo'>",
inlineImages:
{ googleLogo: googleLogoBlob,
youTubeLogo: youtTubeLogoBlob
}
}
);
所以我想做的是像这样转换一个数组:
var array = { item1, item2, item3 };
对于这样的 JSON 对象:
var json = { item1Name: item1,
item2Name: item2,
item3Name: item3
};
这是我正在处理的邮件合并的代码片段:
//---------------------------------------------------------------
// 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});