'javax.mail.util.SharedByteArrayInputStream cannot be cast to javax.mail.Multipart

public  void parseEml(Message msg) throws Exception {
    Address[] froms = msg.getFrom();
    if (froms != null) {
        InternetAddress addr = (InternetAddress) froms[0];
        personalAdd  = addr.getAddress();
        personalName = addr.getPersonal();
    }
    mailSubject = msg.getSubject();
    Object o = msg.getContent();
    msg.writeTo(new FileOutputStream("/sdcard/SoftMail/"+userName+"/temp.eml"));

    if (o instanceof Multipart) {
        Multipart multipart = (Multipart) o ;
        reMultipart(multipart);
    } else if (o instanceof Part) {
        Part part = (Part) o;
        rePart(part);
    } else {
        System.out.println(msg.getContentType());
        System.out.println(msg.getContent());
    }
}

I have "javax.mail.util.SharedByteArrayInputStream cannot be cast to javax.mail.Multipart" problem When I use javax.mail parse email. I have this problem When I use android studio on android platform, but it properly work on Windows platform when I use Eclipse. I don't know why.



Solution 1:[1]

At least for me, the problem was that custom libraries were removing the default mail processing features from JavaMail, so I had to add the MailCap info like posted in the comments. I was using Bouncy Castle, so this solved the problem:

MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gcampos