Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java mail with attachment: ClassCastException on javax.mail.Multipart

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();
}
like image 676
Finder Avatar asked Jan 04 '11 13:01

Finder


1 Answers

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);
}
like image 101
kahlk Avatar answered Oct 02 '22 00:10

kahlk