Retrieve email/message body in html using Gmail AP

2019-03-08 21:08发布

问题:

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 ?

回答1:

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);


回答2:

Both FULL and RAW will return you any text/html parts depending on how you'd like it. If you use FULL you'll get a parsed representation which will be nested json dictionaries that you'll have to walk over looking for the text/html part. If you opt for the RAW format you'll get the entire email in RFC822 format in the Message.raw field. You can pass that to the mime libraries in your chosen language and then use that to find the part you're interested in. Mime is complicated, you'll likely have a top-level "multipart" type with text/html as one of the direct children of it but no guarantees, it's an arbitrarily deep tree structure! :)