Send Gmail Drafts with Inline Images using Google Scripts

The Gmail Scheduler takes your Gmail drafts and send them at the schedule date and time. If a draft email message contains inline images, the ones that that are not hosted on the Internet but have been dragged on to Gmail at the time of composing the message, it uses this routine to parse and include them in the outgoing message.

The getBody() method retrieves the HTML content of a Gmail message but the base64 encoded inline images inside a Gmail draft need to be retrieved using the getRawContent() method. An alternative approach is here.

function sendInlineImages() {
  var message = GmailApp.getDraftMessages()[0];
  var bodyText = message.getBody();
  var rawContent = message.getRawContent();

  // Retrieve the multi-part boundary
  var multipartBoundary = rawContent.match(/multipart\/related; boundary=([\S]*)\s/i);

  // Skip for plain text or HTML emails without inline images
  if (multipartBoundary) {
    // Split the raw content on the multipart boundary to retrieve the inline content.
    var contentParts = rawContent.split('--' + multipartBoundary[1]);

    // Array of base64 encoded inline images
    var inlineImages = {};

    for (var i in contentParts) {
      var contentPart = contentParts[i].trim();

      // If this content part represents base64 encoded inline content?
      if (
        contentPart.match(/content-disposition: inline;/i) &&
        contentPart.match(/content-transfer-encoding: base64/i)
      ) {
        // Extract the mime-type and name.
        var contentType = contentPart.match(/content-type: ([^;]+);\s*name="([^"]+)"/i);
        var mimeType = contentType[1];
        var name = contentType[2];

        // Extract the content-id
        var contentID = contentPart.match(/content-id: <([^>]+)>/i)[1];

        // Split the content part into its header and base64 encoded data.
        // The header and base64 encoded part should be separated by a blank line.
        var subParts = contentPart.split(/^[^\S]+$/m);
        // Regex says split on lines that don't start with a non-space character

        // The 2nd part is the base64 encoded data.
        var base64enc = subParts[1].trim();

        // Create an image blob for the inline content.
        var blob = Utilities.newBlob(Utilities.base64Decode(base64enc), mimeType, contentID);

        inlineImages[contentID] = blob;

        // Replace the image source in the body text with the reference to the inline content.
        var regExp = new RegExp('src="[^"]+realattid=' + contentID + '[^"]+"', 'g');
        bodyText = bodyText.replace(regExp, 'src="cid:' + contentID + '"');
      }
    }
  }

  var subject = message.getSubject();
  var attachments = message.getAttachments();
  var bcc = message.getBcc();
  var cc = message.getCc();

  GmailApp.sendEmail('hello@labnol.org', 'Inline Image Test', 'labnol', {
    attachments: attachments,
    htmlBody: bodyText,
    cc: cc,
    bcc: bcc,
    inlineImages: inlineImages,
  });
}
Amit Agarwal

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

0

Awards & Titles

Digital Inspiration has won several awards since it's launch in 2004.

Google Developer Expert

Google Developer Expert

Google awarded us the Google Developer Expert award recogizing our work in Google Workspace.

ProductHunt Golden Kitty

ProductHunt Golden Kitty

Our Gmail tool won the Lifehack of the Year award at ProductHunt Golden Kitty Awards in 2017.

Microsoft MVP Alumni

Microsoft MVP Alumni

Microsoft awarded us the Most Valuable Professional (MVP) title for 5 years in a row.

Google Cloud Champion

Google Cloud Champion

Google awarded us the Champion Innovator title recognizing our technical skill and expertise.

Email Newsletter

Sign up for our email newsletter to stay up to date.

We will never send any spam emails. Promise.