我有一个班级在这里我读了我的电子邮件(gmail) 我班的代码
Properties props = System.getProperties();
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "mail@gmail.com", "pass");
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_WRITE);
FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
Message messages[] = inbox.search(ft);
for(Message message:messages)
{
Multipart parts = (Multipart)message.getContent();//line 26
Object p = parts.getBodyPart(0).getContent();
String q = p.toString();//object has the body content
//code
}
但我有这个问题
SEVERE: "Servlet.service()" pour la servlet Login a généré une exception
java.lang.ClassCastException: java.lang.String cannot be cast to javax.mail.Multipart
at pack.Testmail.<init>(Testmail.java:26)
at pack.Login.doGet(Login.java:39)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
at java.lang.Thread.run(Unknown Source)
答案 0 :(得分:4)
该特定消息显然不是多部分消息。
https://javamail.java.net/nonav/docs/api/javax/mail/Part.html#getContent()
将内容作为Java对象返回。返回对象的类型 当然取决于内容本身。例如,对象 返回“text / plain”内容通常是一个String对象。该 为“multipart”内容返回的对象始终是Multipart 子类。对于DataHandler未知的内容类型 系统,输入流作为内容返回。这是一个 只调用DataHandler的getContent()的便捷方法 方法
您可以检查部分的MIME类型,以查看它的内容类型。
if (message.isMimeType("message/rfc822")) {
Message message = (Message) part.getContent();
...
}
else if (message.isMimeType("multipart/*")) {
Multipart mp = (Multipart) part.getContent();
for (int i = 0, max = mp.getCount(); i < max; i++) {
...
}
}
else if (message.isMimeType("text/*")) {
String text = (String) part.getContent();
...
}
else {
...
}