我正在尝试使用javamail来检索我的收件箱,但是我现在尝试加载代码时出现了问题,因为读取整个收件箱时要花很多时间才能读取所有电子邮件,但是我只希望很少的电子邮件应该是最新的。
Properties properties = new Properties();
String host = "pop.gmail.com";// change accordingly
properties.put("mail.pop3.host", host);
properties.put("mail.pop3.port", "995");
properties.put("mail.pop3.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);
//create the POP3 store object and connect with the pop server
Store store = emailSession.getStore("pop3s");
store.connect(host, username, password);
//create the folder object and open it
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
// retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
LOG.info("messages.length---" + messages.length);
for (int i = 0; i < messages.length; i++) {
Message message = messages[i];
leadJSONObject = new JSONObject();
LOG.info("Email Number " + (i + 1));
LOG.info("This log is executed successfully");
leadJSONObject.put("emailFrom", message.getFrom()[0].toString());
leadJSONObject.put("emailSubject", message.getSubject());
leadJSONObject.put("emailText", message.getContent().toString());
planJSONArray.put(leadJSONObject);
}
//close the store and folder objects
emailFolder.close(false);
store.close();
请帮助我如何只阅读几封电子邮件。预先感谢。
答案 0 :(得分:1)
您可能希望先统计邮件,然后只检索总数的一部分,例如,获取50条第一条邮件(如果不够的话,则取更少的邮件):
int total = emailFolder.getMessageCount();
Message[] messages = emailFolder.getMessages(1,Math.min(total,50));
cf。 javax.mail.Folder的Javadoc。