Search code examples
javagmailimapjakarta-mail

Convert com.sun.mail.imap.IMAPMessage to string


I am retrieving a message from an IMAP server (Gmail), and trying to print it out, along with some information about it, ultimately to be stored in a string to be parsed later. I am printing out the following

System.out.println(message.getSubject());
System.out.println(message.getFrom()[0]);
System.out.println(message.getReceivedDate());
System.out.println(message.getContent().toString());

and this is what it prints out

Your Order with Amazon.com
"[email protected]" <[email protected]>
Tue Dec 30 23:14:01 EST 2008
javax.mail.internet.MimeMultipart@6baa6838

The first 3 print out exactly what I am expecting, but the last one should be the entire message, should it not? If not, what do I need to do to get it to get the entire message as a string?


Solution

  • IMAPMessage extends MIMEMessage, and according to docs, the getContent() method returns an Object. The type of object is NOT guaranteed to be a String. In your case, the Object that is returned is a MIMEMultipart. Check out this FAQ answer and its example ( msgshow.java) for how to handle a MIMEMultipart object.