I use the following code to download the attachment from the mail but it gives the ClassCastException
on the Multipart declaration:
Exception in thread "main" java.lang.ClassCastException: com.sun.mail.imap.IMAPInputStream cannot be cast to javax.mail.Multipart at ReadAttachment.main(ReadAttachment.java:52)
How do I handle IMAPInputStream?
Message messages[] = inbox.getMessages();
for (int j = 0; j < messages.length; j++) {
String mailType = messages[j].getContentType();
System.out.println("-- Message " + (j + 1) + " --");
System.out.println("SentDate : " + messages[j].getSentDate());
System.out.println("From : " + messages[j].getFrom()[0]);
System.out.println("Subject : " + messages[j].getSubject());
System.out.println("Type :" + messages[j].getContentType());
System.out.println("Attachment :" + messages[j].getFileName());
Multipart mp = (Multipart) messages[j].getContent();
..
System.out.println();
}
I had the same problem with the JavaMail 1.5.1 and OSGi. Using msg.getContent() always returned an InputStream when called from an OSGi bundle while it works perfectly when called from a simple Java test program.
Setting the default CommandMap didn't work for me, but I found a solution here:
https://www.java.net/node/705585
ClassLoader tcl = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(javax.mail.Session.class.getClassLoader());
// now call JavaMail API
// ...
} finally {
Thread.currentThread().setContextClassLoader(tcl);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With