Monday, May 13, 2013

javax.mail.MessagingException: Unable to load BODYSTRUCTURE

This Exception usually comes up when you are using IMAP protocol, and calling part.getDisposition() method. It's a known bug of several IMAP servers. I had this error in GMail when I tried to parse a message with attached .eml file.
If you are facing this issue, create a new MimeMessage based on the one that you're trying to parse. This will force Javamail to download and parse the Mime message locally, and in most cases, it will fix your problem.
Keep the original message, because you still need it to set flags on server (to delete it, for example).

You can do something like this:

public void processMimeMessage(MimeMessage msg) throws MessagingException
    try {
        //some processing
    catch (MessagingException messEx)
        //making sure that it's a BODYSTRUCTURE error
        if (messEx.getMessage() != null && messEx.getMessage().toLowerCase().
        contains("unable to load " +"bodystructure"))
            //creating local copy of given MimeMessage
            MimeMessage msgDownloaded = new MimeMessage((MimeMessage) msg);
            //calling same method with local copy of given MimeMessage
            throw messEx;

from here:

1 comment: