这是用于从Gmail服务器提取电子邮件的代码。随之而来的还有主题和发送者。我正在检查的收件箱中有5条消息(一些已读和一些未读)
我希望html内容可见,所以我使用了JEditorPane

 import javax.mail.*;
 import javax.mail.internet.*;
 import java.util.*;
 import javax.swing.*;

 class NewClass {
 public static void main(String args[]) {
    Properties props = new Properties();
    props.put("mail.imap.host" , "imap.gmail.com" );
    props.put("mail.imap.user" , "username");
    // User SSL
    props.put("mail.imap.socketFactory" , 993);
    props.put("mail.imap.socketFactory.class" , "javax.net.ssl.SSLSocketFactory" );
    props.put("mail.imap.port" , 993 );
    Session session = Session.getDefaultInstance(props , new Authenticator() {
        @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication("username" , "password");
        }
    });

    try {
      Store store = session.getStore("imap");
      store.connect("imap.gmail.com" , "username" , "password");
      Folder fldr = store.getFolder("Inbox");
      fldr.open(Folder.READ_WRITE);
      Message msgs[] = fldr.getMessages();
        for(int i = 0 ; i < msgs.length ; i++) {
            // program breaks after the following statement
            System.out.println(InternetAddress.toString(msgs[i].getFrom()) + "<-- FROM" + " " + msgs[i].getSubject() + "<---Subject");
            JFrame fr = new JFrame();
            JPanel p = new JPanel();
            JEditorPane ep = new JEditorPane("text/html" , (String)msgs[i].getContent());
    ep.setEditable(false);
            JScrollPane sp = new JScrollPane(ep);
            p.add(ep);
            fr.add(p);
            fr.setSize(300,300);
            fr.setVisible(true);
        }
    } catch(Exception exc) {

    }
}


}

我得到的输出是:
Gmail Team <[email protected]><-- FROM Get Gmail on your mobile phone<---Subject

在此输出之后,程序给出以下异常java.lang.ClassCastException: javax.mail.internet.MimeMultipart cannot be cast to java.lang.String at NewClass.main(NewClass.java:34)
为什么框架不可见?

最佳答案

错误在这里

JEditorPane ep = new JEditorPane("text/html" , (String)msgs[i].getContent());


您有多段消息msgs[i].getContent()返回javax.mail.internet.MimeMultipart。您可以对其调用toString,但是正确的方法是从中获取邮件部分。首先,您可以通过instanceof MimeMultipart进行检查。查看JAVAMAIL API FAQ如何处理多部分消息。

10-02 23:23