3

我在这里有一堂课我读了我班级的电子邮件(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)
4

1 回答 1

4

该特定消息显然不是多部分消息。

https://javamail.java.net/nonav/docs/api/javax/mail/Part.html#getContent()

将内容作为 Java 对象返回。返回对象的类型当然取决于内容本身。例如,为“text/plain”内容返回的对象通常是一个字符串对象。为“多部分”内容返回的对象始终是多部分子类。对于 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 {
    ...
}
于 2013-09-13T21:54:18.850 回答