Search code examples
emailgmailmimegmail-api

View message as HTML?


It seems that the Gmail API currently returns the message and message body as MIME. Is it possible to have it return in either plaintext or HTML? If not, is there a way for me to open up the fetched message and view it equivalently to how I would using SMTP?

for (Message message : messages) {
            String messageId = message.getId();
            Message m = service.users().messages().get(userId, messageId).setFormat("full").execute();
            System.out.println("Message toString(): " + m.toString());
            System.out.println("Message getRaw(): "  + m.getRaw());
            System.out.println("Message getPayload().toString(): " + m.getPayload().toString());
            System.out.println("Message getPayload().getBody().getData(): " + m.getPayload().getBody().getData());
            System.out.println("Message getSnippet: " + m.getSnippet());

        }
  1. toString() returns the MIME format (I believe?)
  2. getRaw() returns null
  3. getPayload() returns part of toString()?
  4. getPayload().getBody().getData() returns null
  5. getSnippet returns a plaintext snippet of the message

Gmail guy, which one is most useful if I wish to view it properly? I am assuming toString(). Also, which Java MIME library are you referring to in particular? The libraries I am finding are all mentioning how to determine your MIME type.


Solution

  • You can make your message.get request with format=RAW and get the entire email as one big RFC 2822 string in the Message.raw field of the return type (and parse it using java MIME libraries)

    or (probably better in your case)

    you can make your message.get request with format=FULL and get a parsed message in the message.payload field, which will be tree of parts of the email which you can walk over to find the text/html, text/plain parts, attachments, other parts, etc. MIME formatted emails (anything with more than one part) are a tree structure, etc.