Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not able to display embedded images in HTML using Gmail API + rails

I'm building an app, in which I'm fetching emails from Gmail using Gmail API.

In an email there is 1 image embedded directly in email body(Inline image not attachment). I'm able to extract text/html part and it's displaying properly on browser but in case of inline image, it's showing broken image.

In image tag it's showing as

<img src=\"cid:ii_jfi5vwc30_1628627122d12121\" width=\"454\" height=\"255\">

It's giving content id instead of image url in src. Does anyone know about how should I display inline image using cid in browser page. How should I get image in base64 format from cid?

like image 203
MeeSN Avatar asked Apr 03 '18 11:04

MeeSN


1 Answers

cid: is used as a way to refer to an image attached to a multi-part email, so that the image is an attachment on the email instead of being embedded inline in the email. This means to display your image, you have to look up which attachment contains the referenced image.

Your cid URL corresponds to a Content-ID MIME header that looks like this:

Content-ID: <ii_jfi5vwc30_1628627122d12121>

The Gmail API should have given you a response that looks something like this:

{
  "parts": [
    // ... other parts ...
    {
      "partId": "1",
      "mimeType": "image/png",
      "filename": "",
      "headers": [
        {
          "name": "Content-ID",
          "value": "<ii_jfi5vwc30_1628627122d12121>"
        },
        {
          "name": "Content-Type",
          "value": "image/png"
        },
        {
          "name": "Content-Transfer-Encoding",
          "value": "base64"
        }
      ],
      "body": {
        "size": 9999,
        "data": "R0lGODlhGAGgAPEAAP...(the original base64 encoded image)",
      }
    }
    // ... other parts ...
  ]
  // ... rest of response ...
}

In order to display the image, you'll need to go back through the response object and find the header with a name of Content-ID and a value of ii_jfi5vwc30_1628627122d12121, and then parse the object in order to read its body.data, which is the base64 encoded image you desire.

If the response does not include this part, then it means the original email was malformed or the associated image was not correctly attached to the email in some way, and then you're out of luck and there is no way to render the original image.

like image 173
Bill Mei Avatar answered Oct 03 '22 18:10

Bill Mei