Skip to content

Instantly share code, notes, and snippets.

@mhawksey
Last active April 2, 2021 05:50
Show Gist options
  • Save mhawksey/f01cd9faa6cb2325e0f3f449ac0e6005 to your computer and use it in GitHub Desktop.
Save mhawksey/f01cd9faa6cb2325e0f3f449ac0e6005 to your computer and use it in GitHub Desktop.
Handling inline images and attachments so they can be included in the merge
// Handling inline images and attachments so they can be included in the merge
// Based on https://stackoverflow.com/a/65813881/1027723
// Get all attachments and inline image attachments
const msg = draft.getMessage();
const allInlineImages = msg.getAttachments({includeInlineImages: true, includeAttachments: false});
const attachments = msg.getAttachments({includeInlineImages: false});
const htmlBody = msg.getBody();
// Create an inline image object with the image name as key
// (can't rely on image index as array built based on insert order)
const img_obj = allInlineImages.reduce((obj, i) => (obj[i.getName()] = i, obj) ,{});
// Regex to search for all img string positions with cid and alt
const imgexp = RegExp('<img.*?src="cid:(.*?)".*?alt="(.*?)"[^\>]+>', 'g');
const matches = [...htmlBody.matchAll(imgexp)];
// Initiate the allInlineImages object
const inlineImagesObj = {};
// built an inlineImagesObj from inline image matches
// match[1] = cid, match[2] = alt
matches.forEach(match => inlineImagesObj[match[1]] = img_obj[match[2]]);
GmailApp.sendEmail(recipient, subject, '', {
name:senderName,
from:senderEmail,
htmlBody:htmlBody,
cc:allCc,
bcc:bcc,
attachments: attachments,
inlineImages: inlineImagesObj
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment