0
votes

I am trying to fetch the emails body using Gmail Java APIs. I am getting all the fields including to, from, subject.

But I am not able to get the textual body, also html body of email here is my code fragment :

 List<MessagePart> parts =  message.getPayload().getParts();
            StringBuilder textSb = new StringBuilder();
            StringBuilder htmlSb = new StringBuilder();
            for (MessagePart part : parts) {
                if (part.getMimeType().equalsIgnoreCase("text/plain")) {
                    try {
                        textSb.append(new String(Base64.getDecoder().decode(part.getBody().getData()), "UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }

                if (part.getMimeType().equalsIgnoreCase("text/html")) {
                    try {
                        htmlSb.append(new String(Base64.getDecoder().decode(part.getBody().getData()), "UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
            }

An short email body text-snippet can be obtained using below method ( But not full body ) :

message.getSnippet();

But thats not enough in my case I need whole body contents.

While iterating over MessageParts in above loop in debugger I am getting two parts first with MIME type multipart/alternative and other of MIME type application/pdf which is for pdf file attachment.

What should I do to get the body of email ?

1

1 Answers

1
votes

After searching more, I found that the details are in first part of the MessageParts List of Message object. In this first part you will get the List of MessageParts which contains the body of email i.e. textual content, html content :

    List<MessagePart> parts = message.getPayload().getParts().get(0).getParts();
    StringBuilder mixContent = new StringBuilder();

    for (MessagePart part : parts) {
                    if (part.getMimeType().equalsIgnoreCase("text/plain")) {
                        try {
                            mixContent.append(new String(Base64.getUrlDecoder().decode(part.getBody().getData()), "UTF-8"));
                            continue;
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                    if (part.getMimeType().equalsIgnoreCase("text/html")) {
                        try {
                             mixContent.append(new String(Base64.getUrlDecoder().decode(part.getBody().getData()), "UTF-8"));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                }