How to Send Base64 Images in Email with Google Apps Script

Base64-encoded images can be embedded directly inside HTML emails without having to host the image on a remote server. This offers several advantages:

  1. Avoids tracking - External images are often used by email marketers to track email opens.
  2. Reduced spam potential - Some email servers may reject emails that contain external images.
  3. 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



source:https://ift.tt/vgt0JoP

Comments

Popular posts from this blog

The 101 Most Useful Websites

How to Embed the Facebook Customer Chat Widget in your Website