我有一个包含GUI的应用程序,它使用的是Javamail。当我打开此Jframe
时,我必须在jTextArea
上看到发送到我邮件的邮件。
问题在于,当我编写代码时,它只显示最后发送的消息。
如何在收件箱中显示所有新讯息?
这是我的代码:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Properties props = new Properties();
props.put("mail.pop3.host", "pop.gmail.com");
props.put("mail.pop3.user", "mymail@gmail.com");
props.put("mail.pop3.socketFactory", 995);
props.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.pop3.port", 995);
Session session = Session.getDefaultInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("mymail@gmail.com", "mypassword");
}
});
try {
Store store = session.getStore("pop3");
store.connect("pop.gmail.com", "mymail@gmail.com", "mypaswword");
Folder fldr = store.getFolder("INBOX");
fldr.open(Folder.READ_ONLY);
Message[] msg = fldr.getMessages();
Address[] address;
for (int i = 0; i < msg.length; i++) {
jTextArea1.setText("SentDate : " + msg[i].getSentDate() + "\n" + "From : " + msg[i].getFrom()[0] + "\n" + "Subject : " + msg[i].getSubject() + "\n" + "Message : " + "\n" + msg[i].getContent().toString());
}
fldr.close(true);
store.close();
} catch (Exception e) {
System.out.println(e);
}
答案 0 :(得分:0)
您在此处重复将jTextArea1
的文本设置为循环中的相同内容:
for (int i = 0; i < msg.length; i++) {
jTextArea1.setText("SentDate : " + msg[i].getSentDate() + "\n" + "From : " + msg[i].getFrom()[0] + "\n" + "Subject : " + msg[i].getSubject() + "\n" + "Message : " + "\n" + msg[i].getContent().toString());
}
您应该使用所有消息构建StringBuilder
,然后设置jTextArea1
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < msg.length; i++) {
sb.append("SentDate : " + msg[i].getSentDate() + "\n" + "From : " + msg[i].getFrom()[0] + "\n" + "Subject : " + msg[i].getSubject() + "\n" + "Message : " + "\n" + msg[i].getContent().toString());
}
jTextArea1.setText(sb.toString());
然后,您可以使用增强的for循环并使用append
的{{1}}方法,使其更加清晰。
StringBuilder
答案 1 :(得分:0)
final StringBuilder sb = new StringBuilder();
for (Message message : msg) {
sb.append("SentDate : ").
append(message.getSentDate()).
append("\n").
append("From : ").
append(message.getFrom()[0]).
append("\n").append("Subject : ").
append(message.getSubject()).
append("\n").
append("Message : ").
append("\n").
append(message.getContent().toString());
}
jTextArea1.setText(sb.toString());