如何使用Java Mail API获取有限数量的消息

时间:2018-02-27 23:44:15

标签: java javamail indexoutofboundsexception

我正在使用此代码加载收件箱邮件。

// connect to my pop3 inbox
Properties properties = System.getProperties();
Session session = Session.getDefaultInstance(properties);
Store store = null;
try {
    store = session.getStore("pop3");

    store.connect(inboxAccountConfiguration.getServerAddress(), inboxAccountConfiguration.getUserName(), inboxAccountConfiguration.getPassword());
    Folder inbox = store.getFolder("Inbox");
    inbox.open(Folder.READ_ONLY);

    // get the list of inbox messages
    Message[] messages = inbox.getMessages();

    if (messages.length == 0) System.out.println("No messages found.");

    for (int i = 0; i < messages.length; i++) {
        // stop after listing ten messages
        if (i > 10) {
            System.exit(0);
            inbox.close(true);
            store.close();
        }

        System.out.println("Message " + (i + 1));
        System.out.println("From : " + messages[i].getFrom()[0]);
        System.out.println("Subject : " + messages[i].getSubject());
        System.out.println("Sent Date : " + messages[i].getSentDate());
        System.out.println();
    }

    inbox.close(true);
    store.close();
} catch (Exception e) {
    e.printStackTrace();
}

但是我需要限制加载的消息数量

我已经尝试了类似的东西

Message[] messages = inbox.getMessages(0, (int) configuration.getNumber());

但这不起作用,只是抛出异常

java.lang.ArrayIndexOutOfBoundsException: -1
    at com.sun.mail.pop3.POP3Folder.getMessage(POP3Folder.java:364)
    at javax.mail.Folder.getMessages(Folder.java:933)
    at core.mail.POPMessageRetriever.lambda$getInboxMail$0(POPMessageRetriever.java:33)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

如何只加载特定数量的收件箱邮件?

1 个答案:

答案 0 :(得分:1)

消息的编号从1开始,而不是0。

getMessages方法不加载任何消息。它仅创建一个Message对象,该对象充当对服务器上的消息的引用。消息数据仅在Message对象上的某个方法需要时加载。