Does JavaMail support Multipart nesting?

Dieter Wimberger

It is possible to access all the parts of a message, even if they are nested multiparts. One possible approach is to work recursively and "flatten" out the parts into one straight list (this is the one I prefer, even if it does not reflect exactly how the message looks like "architecturally").
You start from:

if(msg.isMimeType("multipart/*")) {
  //get main body part
  Multipart mp=(Multipart)msg.getContent();
  //build flatlist					
  List partlist=new ArrayList(10);	//example, use your own size idea
And the recursive method is:
private void buildPartInfoList(List partlist, Multipart mp) 
    throws Exception {
  for (int i=0; i<mp.getCount(); i++) {
    //Get part
    Part apart=mp.getBodyPart(i);
    //handle single & multiparts
    if(apart.isMimeType("multipart/*")) {
    } else {
      //append the part
The list partlist will afterwards contain all the parts that have been encountered with the multipart message.

If you do not like this approach, you can easily extract the idea of how to retrieve a specific nested part from the code above.