Search code examples
javaandroidgmail-api

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

}

Solution

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