0

I'm trying to read the content of mail using JavaMail

Object msg = message.getContent();
Multipart mp = (Multipart) msg;
for(int k = 0; k < mp.getCount(); k++) {
    BodyPart bp = mp.getBodyPart(k);
    if (bp.isMimeType("text/plain")) {
        String s = (String) bp.getContent();
        System.out.println("Content:" + s);
    }
    else if(bp.isMimeType("text/html")) {
        String s = (String) bp.getContent();
        System.out.println("Content:" + s);
    }
}

But I'm getting the following error:

java.lang.ClassCastException: java.lang.String cannot be cast to javax.mail.Multipart

How can I remove this?

Sean F
  • 2,352
  • 3
  • 28
  • 40
Gaurav Mahawar
  • 412
  • 3
  • 5
  • 14

3 Answers3

1
Object msg = message.getContent();
Multipart mp = (Multipart) msg;

message.getContent() not necessarily needs to be multipart message - if it's not multipart, it returns plain message content as a string.

if (msg istanceof Multipart) {
    // your multipart handling code
} else {
    String s = (String) msg;
    System.out.println("Content:" + s);
}

-edit-

There is also third case, when input stream is returned: http://docs.oracle.com/javaee/6/api/javax/mail/Part.html#getContent()

Rafał Wrzeszcz
  • 1,996
  • 4
  • 23
  • 45
1

The type of the returned object is dependent on the content itself. The object returned for text/plain content is usually a String object. The object returned for a multipart content is always a Multipart subclass.

Use perator instanceof, to find out what class of the object.

Object content = message.getContent();  
if(content instanceof String) {  
   ...
} else if(content instanceof Multipart) {  
    ...  
}  
0

It seems the email sent is not of Multipart content type. Check if the email has attachments first:

String contentType = message.getContentType();

if (contentType.contains("multipart")) {

}
Tony Vu
  • 4,251
  • 3
  • 31
  • 38