简体   繁体   中英

JavaMail : Folder.hasNewMessages() and .getMessageCount() don't seem to work properly

I have this simple code to perdiodically access a pop3 server and check if there are new messages in the inbox folder

public static void main(String[] args) {


    try {

        String storeType = "pop3";

        String host = "...";
        int port = ...;
        String user = "...";
        String psw = "...";

        //
        int delay = 1;
        long mins = 200 * 60 * delay;
        firstAccess = true;


        Properties properties = new Properties();
        properties.put("mail.pop3.host", host);
        properties.put("mail.pop3.user", user);
        properties.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.pop3.port", port);


        RomasAuthenticator r = new RomasAuthenticator(user, psw);

        Session session = Session.getDefaultInstance(properties, r);

        POP3Store emailStore = (POP3Store) session.getStore(storeType);
        emailStore.connect(host, port, user, psw);

        Folder emailFolder = emailStore.getFolder("INBOX");
        emailFolder.open(Folder.READ_ONLY);

        while (true) {
            if (checkInbox(emailFolder)) {
                //prepara la notifica per il voice_service
                System.out.println("mes!");
            }
            firstAccess = false;
            Thread.sleep(mins);
        }




    } catch (Exception ex) {
        //return null;
    }
}


private static boolean checkInbox(Folder inbox_folder) throws MessagingException, IOException {
    System.out.println("checking");
    boolean res = false;

    try {

        int email_actual_count = inbox_folder.getMessageCount();

        if (email_actual_count > email_prev_count /*or hasNewMessages()*/) {
            if (!firstAccess) {
                res = true;
            }
        }

        //bisogna aggiornare comunque email_count in caso siano stati cancellati messaggi
        email_prev_count = email_actual_count;

    } 

    catch (Exception e) {
        e.printStackTrace();
    }

    return res;

}

Both getMessageCount() and hasNewMessages() do not work, because the first always returns the same number of messages, and the second always returns false. What's that I'm doing wrong? I don't want to use a messagelistener because this code will run on a robot with really low performances.. thanks everyone

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM