我正在使用 JavaMail API 为我的 Android 手机开发电子邮件客户端。如果我尝试获取电子邮件的内容,我会在 logCat 中获得以下文本:
发件人:XXXXXXXXXXXXXXXXXXXXXXXXXXX
至:AG Blasorchester
主题:咬牙切齿 SCHWARZE MAPPE / RINGORDNER
发送日期:2013 年 2 月 27 日星期三 21:30:49 MEZ
内容类型:文本/纯文本;字符集=iso-8859-1
留言内容:
Fehler:java.lang.ClassCastException:com.sun.mail.util.QPDecoderStream 无法转换为 java.lang.String
这是抛出的异常:java.lang.ClassCastException: com.sun.mail.util.QPDecoderStream cannot be cast to java.lang.String
我使用以下代码获取内容:
public static void dumpPart(Part p) throws Exception {
Log.i("Gestartet", "dumpPart Gestartet");
if (p instanceof Message)
dumpEnvelope((Message)p);
/** Dump input stream ..
InputStream is = p.getInputStream();
// If "is" is not already buffered, wrap a BufferedInputStream
// around it.
if (!(is instanceof BufferedInputStream))
is = new BufferedInputStream(is);
int c;
while ((c = is.read()) != -1)
System.out.write(c);
**/
String ct = p.getContentType();
try {
pr("CONTENT-TYPE: " + (new ContentType(ct)).toString());
} catch (ParseException pex) {
pr("BAD CONTENT-TYPE: " + ct);
}
String filename = p.getFileName();
if (filename != null)
pr("FILENAME: " + filename);
/*
* Using isMimeType to determine the content type avoids
* fetching the actual content data until we need it.
*/
try{
if (p.isMimeType("text/plain")) {
pr("This is plain text");
pr("---------------------------");
if (!showStructure && !saveAttachments)
System.out.println((String)p.getContent());
} else if (p.isMimeType("multipart/*")) {
pr("This is a Multipart");
pr("---------------------------");
Multipart mp = (Multipart)p.getContent();
level++;
int count = mp.getCount();
for (int i = 0; i < count; i++)
dumpPart(mp.getBodyPart(i));
level--;
} else if (p.isMimeType("message/rfc822")) {
pr("This is a Nested Message");
pr("---------------------------");
level++;
dumpPart((Part)p.getContent());
level--;
} else {
if (!showStructure && !saveAttachments) {
/*
* If we actually want to see the data, and it's not a
* MIME type we know, fetch it and check its Java type.
*/
Object o = p.getContent();
if (o instanceof String) {
pr("This is a string");
pr("---------------------------");
System.out.println((String)o);
} else if (o instanceof InputStream) {
pr("This is just an input stream");
pr("---------------------------");
InputStream is = (InputStream)o;
int c;
while ((c = is.read()) != -1)
System.out.write(c);
} else {
pr("This is an unknown type");
pr("---------------------------");
pr(o.toString());
}
} else {
// just a separator
pr("---------------------------");
}
}
}catch(Exception e){
Log.i("Fehler", "Fehler: " + e);
}
}
我可以毫无例外地将消息内容作为字符串获取吗?