Retrieve email/message body in html using Gmail API

Kartik Domadiya picture Kartik Domadiya · Jun 26, 2014 · Viewed 20.5k times · Source

Is there any way to retrieve message body in html form using GMail api ?

I have already gone through the message.get docs. Tried changing the format param to full, minimal & raw. But it did not help. It's returning the plain text of mail body.


Description of format values:

"full": Returns the parsed email message content in the payload field and the raw field is not used. (default)

"minimal": Only returns email message metadata such as identifiers and labels, it does not return the email headers, body, or payload.

"raw": Returns the entire email message content in the raw field as a string and the payload field is not used. This includes the identifiers, labels, metadata, MIME structure, and small body parts (typically less than 2KB).


Can't we simply get message body in html form or is there any other way to do this so that mail is displayed on the screen with very minimal difference when they see in my app or GMail ?

Answer

Eric Koleda picture Eric Koleda · Jun 26, 2014

Email messages that have both HTML and plain text content will have multiple payload parts, and the part with the mimeType "text/html" will contains the HTML content. You can find it with logic like:

var part = message.parts.filter(function(part) {
  return part.mimeType == 'text/html';
});
var html = urlSafeBase64Decode(part.body.data);