emailgoogle-apps-scriptgmailinline-images

How to include inline images in email using MailApp


I have a simple MailApp to send text in HTML format. The small question I have is: How do I insert inline images in that text? For example, I want to add a Dutch flag for the Dutch text, and a French flag for the French content.

I assumed just using HTML code would do the job. But alas, no such luck. It's just a tiny image I need, no big images below the content. How can I accomplish this?

MailApp.sendEmail(mailaddress, subject, "" ,
              { htmlBody: bodyNL + bodyFR })

Solution

  • The documention for sendEmail(message) shows how to add two logos to an email as inline images.

    Here's an adaptation from Google's example that will prepend your text blocks with their locale flags. It uses images from Wikimedia, which are freely licensed under Creative Commons.

    screenshot

    The keys to how this works are:

    Code:

    /**
     * Example of sending an HTML email message with inline images.
     * From: http://stackoverflow.com/a/37688529/1677912
     */
    function sendInlineImages() {
      var mailaddress = Session.getActiveUser().getEmail();
      var subject = "test inline images";
      var bodyNL = "This is <B>DUTCH</B> text.";
      var bodyFR = "This is <B>FRENCH</B> text.";
    
      // Image URLs, under CC license
      var nlFlagUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b2/Flag_of_the_Netherlands.png/320px-Flag_of_the_Netherlands.png";
      var frFlagUrl = "https://upload.wikimedia.org/wikipedia/en/thumb/c/c3/Flag_of_France.svg/320px-Flag_of_France.svg.png";
    
      // Fetch images as blobs, set names for attachments
      var nlFlagBlob = UrlFetchApp
                                .fetch(nlFlagUrl)
                                .getBlob()
                                .setName("nlFlagBlob");
      var frFlagBlob = UrlFetchApp
                                .fetch(frFlagUrl)
                                .getBlob()
                                .setName("frFlagBlob");
    
      // Prepend embeded image tags for email
      bodyNL = "<img src='cid:nlFlag' style='width:24px; height:16px;'/>" + bodyNL;
      bodyFR = "<img src='cid:frFlag' style='width:24px; height:16px;'/>" + bodyFR;
    
      // Send message with inlineImages object, matching embedded tags.
      MailApp.sendEmail(mailaddress, subject, "",
                        { htmlBody: bodyNL + "<BR/><BR/>" + bodyFR,
                          inlineImages:
                          {
                            nlFlag: nlFlagBlob,
                            frFlag: frFlagBlob
                          }
                        });
    
    }