这是用于从 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 <mail-noreply@google.com><-- 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)
。为什么框架不可见?