Does JavaMail support Multipart nesting?
Created May 7, 2012
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:
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 buildPartInfoList(partlist,mp); } [...]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/*")) { //recurse buildPartInfoList(partlist,(Multipart)apart.getContent()); } else { //append the part partlist.add(apart); } } }//buildPartList [...]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.