0

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

}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Ayush Gupta
  • 1,589
  • 3
  • 13
  • 23

3 Answers3

5
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);
    }
  • This answer really helped me solve an issue I was stuck on for 4-5 hours !! thanks @Kiran Palaka – Dinesh Oct 23 '16 at 22:54
  • Help, Im getting a nullpointer in "part.getBody().getData()" because "part.getBody()" returns an array of DataMap$Entry – Pedro Joaquín Oct 09 '20 at 14:57
  • Unfortunately, I get an error `the return value of "com.google.api.services.gmail.model.Message.getPayload()" is null` – Zoette Aug 30 '22 at 03:34
1

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.

Henk
  • 176
  • 1
  • 7
-1

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