How to Send Base64 Images in Email with Google Apps Script
Gmail will not render base64 images embedded inside HTML emails but with Google Apps Script, you can use blobs to send the base64 encoded images
Base64-encoded images can be embedded directly inside HTML emails without having to host the image on a remote server. This offers several advantages:
- Avoids tracking - External images are often used by email marketers to track email opens.
- Reduced spam potential - Some email servers may reject emails that contain external images.
- No broken images - If the image is hosted on a remote server, it may not load if the server is down.
Gmail, however, does not support base64 images in HTML emails. If you try to send an email with base64 images to a Gmail or Google Workspace account, the image will not be displayed in the email body but will be displayed as an attachment instead.
The workaround is to convert the base64 image to a blob and then embed the blob in the email. We use a similar technique to embed base64 encoded images in emails sent from Mail Merge and Document Studio.
The following Google Apps Script function will convert all base64 images in an HTML email to blobs and then send the email using the Gmail service.
// The original HtmlMessage may contain base64 images in the <img> tags.
// <img src="data:image/png;base64,R0lGODlhQABAAMQAAJSWl..." />
const sendEmailWithGmail = ({ to, subject, htmlMessage }) => {
let htmlBody = htmlMessage;
const inlineImages = {};
// Find all base64 image tags in the html message.
const base64ImageTags = htmlBody.match(/<img src="data:image\/(png|jpeg|gif);base64,([^"]+)"[^>]*>/gm) || [];
base64ImageTags.forEach((base64ImageTag) => {
// Extract the base64-encoded image data from the tag.
const [, format, base64Data] = base64ImageTag.match(/data:image\/(png|jpeg|gif);base64,([^"]+)/);
// Convert the base64 data to binary.
const imageByte = Utilities.base64Decode(base64Data);
// Create a blob containing the image data.
const imageName = Utilities.getUuid();
const imageBlob = Utilities.newBlob(imageByte, `image/${format}`, imageName);
// Replace the base64 image tag with cid: image tag.
const newImageTag = base64ImageTag.replace(/src="[^"]+"/, `src="cid:${imageName}"`);
htmlBody = htmlBody.replace(base64ImageTag, newImageTag);
inlineImages[imageName] = imageBlob;
});
MailApp.sendEmail({
to: to,
subject: subject,
htmlBody: htmlBody,
inlineImages: inlineImages,
});
};
Also see: Send Emails with Gmail API
Amit Agarwal
Google Developer Expert, Google Cloud Champion
Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India.
Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory