Retrieve UnRead Emails from Gmail – JavaMail API + IMAP

You’re using the same index to get a message from your list as to get a part from that message. So you’re fetching part 1 from message 1, part 2 from message 2, etc. At some point, you’ll hit a message N that has fewer than N parts, and you get the ArrayIndexOutOfBoundsException.

Multipart mp = (Multipart)messages[i].getContent();  
Object p = mp.getBodyPart(i).getContent();  

Also, you’re assuming that all your messages are multipart. The first time you call Message.getContent() on a non-multipart message, you’ll get a ClassCastException as it’ll most likely be returning you a String instead.

Multipart mp = (Multipart)messages[i].getContent();  

Similarly, you’re assuming non-nested multiparts. The first time you get a message with a top-level multipart/mixed containing a multipart/alternative as its first subpart, the call to MimeBodyPart.getContent() will return another Multipart and thus p.toString() will just return a Java object identifier, not the message content you want.

Object p = mp.getBodyPart(i).getContent();  
String q = p.toString();//object has the body content  

To do it right, you need to walk the message structure and determine the “body” part you care about.

Leave a Comment