Ayush Gupta
Ayush Gupta

Reputation: 1727

Gmail APIs: Decoding the body of the message (Java/Android)

I need to get the retrieved mail in the format it was in the user mailbox, i.e.: HTML.
I am having troubles decoding the body of the retrieved message.

Please suggest a method for getting this done in Java.

I am currently doing this to get the message:

public class MyClass {

  public static Message getMessage(Gmail service, String userId, String messageId)
      throws IOException {
    Message message = service.users().messages().get(userId, messageId).execute();

    System.out.println("Message snippet: " + message.getSnippet());

    return message;
  }

  public static MimeMessage getMimeMessage(Gmail service, String userId, String messageId)
      throws IOException, MessagingException {
    Message message = service.users().messages().get(userId, messageId).setFormat("raw").execute();

    byte[] emailBytes = Base64.decodeBase64(message.getRaw());

    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session, new ByteArrayInputStream(emailBytes));

    return email;
  }

}

Upvotes: 0

Views: 3012

Answers (3)

Yunier Broche Guevara
Yunier Broche Guevara

Reputation: 309

new String(messageResult.getPayload().getParts().get(0).getBody().decodeData())

Upvotes: -1

Henk
Henk

Reputation: 176

You could use the following methods:

private String getContent(Message message) {
    StringBuilder stringBuilder = new StringBuilder();
    try {
        getPlainTextFromMessageParts(message.getPayload().getParts(), stringBuilder);
        byte[] bodyBytes = Base64.decodeBase64(stringBuilder.toString());
        String text = new String(bodyBytes, "UTF-8");
        return text;
    } catch (UnsupportedEncodingException e) {
        logger.error("UnsupportedEncoding: " + e.toString());
        return message.getSnippet();
    }
}

private void getPlainTextFromMessageParts(List<MessagePart> messageParts, StringBuilder stringBuilder) {
    for (MessagePart messagePart : messageParts) {
        if (messagePart.getMimeType().equals("text/plain")) {
            stringBuilder.append(messagePart.getBody().getData());
        }

        if (messagePart.getParts() != null) {
            getPlainTextFromMessageParts(messagePart.getParts(), stringBuilder);
        }
    }
}

It combines all message parts with the mimeType "text/plain" and returns it as one string.

Upvotes: 1

Kiran Palaka
Kiran Palaka

Reputation: 86

String mimeType = message.getPayload().getMimeType();
    List<MessagePart> parts = message.getPayload().getParts();
    if (mimeType.contains("alternative")) {
        log.info("entering alternative loop");
        for (MessagePart part : parts) {
            mailBody = new String(Base64.decodeBase64(part.getBody()
                    .getData().getBytes()));

        }
        log.info(mailBody);
    }

Upvotes: 5

Related Questions