So I have a draft email looks like this :
and this is how my email looks after mailing it
I can find those images in email as attachment like this
and here is my script I am using so can anyone here tell me if I am doing something wrong and what is wrong in this code, because idk much about google app script, I just found this script from the stack I am not able to find that post again so couldn't upload its link.
function main( ) {
var thread = GmailApp.getDrafts()[0];
var TemplateMessage = thread.getMessage();
Logger.log(TemplateMessage.getSubject());
var emailTemplate = TemplateMessage.getBody();
var rawContent = TemplateMessage.getRawContent();
var attachments = TemplateMessage.getAttachments();
var regMessageId = new RegExp(TemplateMessage.getId(), "g");
if (emailTemplate.match(regMessageId) != null) {
var inlineImages = {};
var nbrOfImg = emailTemplate.match(regMessageId).length;
var imgVars = emailTemplate.match(/<img[^>]+>/g);
var imgToReplace = [];
if(imgVars != null){
for (var i = 0; i < imgVars.length; i++) {
if (imgVars[i].search(regMessageId) != -1) {
var id = imgVars[i].match(/realattid=([^&]+)&/);
if (id != null) {
var temp = rawContent.split(id[1])[1];
temp = temp.substr(temp.lastIndexOf('Content-Type'));
var imgTitle = temp.match(/name="([^"]+)"/);
if (imgTitle != null) imgToReplace.push([imgTitle[1], imgVars[i], id[1]]);
}
}
}
}
for (var i = 0; i < imgToReplace.length; i++) {
for (var j = 0; j < attachments.length; j++) {
if(attachments[j].getName() == imgToReplace[i][0]) {
inlineImages[imgToReplace[i][2]] = attachments[j].copyBlob();
attachments.splice(j, 1);
var newImg = imgToReplace[i][1].replace(/src="[^\"]+\"/, "src=\"cid:" + imgToReplace[i][2] + "\"");
emailTemplate = emailTemplate.replace(imgToReplace[i][1], newImg);
}
}
}
}
//////////////////////////////////////////////////////////////////////////////
var message = {
htmlBody: emailTemplate,
subject: TemplateMessage.getSubject(),
attachments: attachments,
inlineImages: inlineImages
}
GmailApp.sendEmail(Session.getActiveUser().getEmail(), TemplateMessage.getSubject(), "", message);
}