Methods to Ship Base64 Pictures in E mail with Google Apps Script

Shubham
3 Min Read

Base64-encoded photographs could be embedded instantly inside HTML emails with out having to host the picture on a distant server. This provides a number of benefits:

  1. Avoids monitoring – Exterior photographs are sometimes utilized by electronic mail entrepreneurs to track email opens.
  2. Diminished spam potential – Some electronic mail servers could reject emails that comprise exterior photographs.

  3. No damaged photographs – If the picture is hosted on a distant server, it could not load if the server is down.

Gmail, nevertheless, doesn’t assist base64 photographs in HTML emails. When you attempt to ship an electronic mail with base64 photographs to a Gmail or Google Workspace account, the picture won’t be displayed within the electronic mail physique however will likely be displayed as an attachment as an alternative.

The workaround is to transform the base64 picture to a blob after which embed the blob within the electronic mail. We use an analogous method to embed base64 encoded photographs in emails despatched from Mail Merge and Document Studio.

The next Google Apps Script operate will convert all base64 photographs in an HTML electronic mail to blobs after which ship the e-mail utilizing the Gmail service.

// The unique HtmlMessage could comprise base64 photographs within the  tags.
// 

const sendEmailWithGmail = ({ to, topic, htmlMessage }) => {
  let htmlBody = htmlMessage;
  const inlineImages = {};

  // Discover all base64 picture tags within the html message.
  const base64ImageTags = htmlBody.match(//(png"https://www.labnol.org/jpeg"https://www.labnol.org/gif);base64,([^"]+)"https://www.labnol.org/[^>]*>/gm) |"https://www.labnol.org/ [];

  base64ImageTags.forEach((base64ImageTag) => {
    // Extract the base64-encoded picture knowledge from the tag.
    const [, format, base64Data] = base64ImageTag.match(/knowledge:picture/(png"https://www.labnol.org/jpeg"https://www.labnol.org/gif);base64,([^"]+)/);

    // Convert the base64 knowledge to binary.
    const imageByte = Utilities.base64Decode(base64Data);

    // Create a blob containing the picture knowledge.
    const imageName = Utilities.getUuid();
    const imageBlob = Utilities.newBlob(imageByte, `picture/${format}`, imageName);

    // Substitute the base64 picture tag with cid: picture tag.
    const newImageTag = base64ImageTag.exchange(/src="https://www.labnol.org/[^"]+"/, `src="https://www.labnol.org/cid:${imageName}"`);
    htmlBody = htmlBody.exchange(base64ImageTag, newImageTag);

    inlineImages[imageName] = imageBlob;
  });

  MailApp.sendEmail({
    to: to,
    topic: topic,
    htmlBody: htmlBody,
    inlineImages: inlineImages,
  });
};

Additionally see: Ship Emails with Gmail API

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *