What is the type for part.getContent in JavaMail under different os?
I am using JavaMail to receive mails. At first,I develop under Mac OS X.The example I found from Internet seems like this:
public void getMailContent(Part part) throws Exception {
String contenttype = part.getContentType();
int nameindex = contenttype.indexOf("name");
boolean conname = false;
if (nameindex != -1)
conname = true;
System.out.println("CONTENTTYPE: " + contenttype);
if (part.isMimeType("text/plain") && !conname) {
bodytext.append((String) part.getContent());
} else if (part.isMimeType("text/html") && !conname) {
bodytext.append((String) part.getContent());
} else if (part.isMime开发者_Python百科Type("multipart/*")) {
Multipart multipart = (Multipart) part.getContent();
int counts = multipart.getCount();
for (int i = 0; i < counts; i++) {
getMailContent(multipart.getBodyPart(i));
}
} else if (part.isMimeType("message/rfc822")) {
getMailContent((Part) part.getContent());
} else {}
}
But I found it don't work.The return value is a extends of InputStream. So I use this to solve the problem.
InputStreamReader isr = new InputStreamReader((InputStream) part.getContent(), language);
BufferedReader br = new BufferedReader(isr);
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
result = MimeUtility.decodeText(sb.toString());
But recently,I got a new pc and run the code above under Windows 7,It don't work also.The exception is java.lang.String cannot be cast to java.io.InputStream
.The part.getContent() returns a String as the example on internet.
I just don't know the reason.And how to run is properly on both mac and windows or any way to avoid this issue and get the content of the part.
Thanks.
I faced the same problem, found the reason (though, I suppose, this is not necessarily the only reason that may lead to the problem), and fixed it, so I decided to post the solution.
In my case, I was building Android application. In Android, some classes are missing in its javax.security package, so the asmack helper package was used, and JavaMail library has been built from sources.
The problem was, that I did not pack required resources into the javamail jar. Specifically, the following files should be packed while exporting the jar:
- dsn.mf
- javamail.charset.map
- javamail.default.address.map
- javamail.default.providers
- javamail.imap.provider
- javamail.pop3.provider
- javamail.smtp.address.map
- javamail.smtp.provider
- mailcap
After the fix, I'm getting properly decoded content just from the getContent
method. The clue was found on this page.
Scanner sc=new Scanner(contenttype);
while(sc.hasNext()){
sc.next();
}
use this piece of code.....modify according to your need....and you dont need to do the typecasting.
I solved my own problem by using instanceof
, though I still don't know why this works.
精彩评论