Search in sources :

Example 1 with MessageCountAdapter

use of javax.mail.event.MessageCountAdapter in project Openfire by igniterealtime.

the class EmailListener method listenMessages.

private void listenMessages() {
    try {
        // Add messageCountListener to listen for new messages
        messageListener = new MessageCountAdapter() {

            @Override
            public void messagesAdded(MessageCountEvent ev) {
                Message[] msgs = ev.getMessages();
                // Send new messages to specified users
                for (Message msg : msgs) {
                    try {
                        sendMessage(msg);
                    } catch (Exception e) {
                        Log.error("Error while sending new email message", e);
                    }
                }
            }
        };
        folder.addMessageCountListener(messageListener);
        // Check mail once in "freq" MILLIseconds
        int freq = getFrequency();
        boolean supportsIdle = false;
        try {
            if (folder instanceof IMAPFolder) {
                IMAPFolder f = (IMAPFolder) folder;
                f.idle();
                supportsIdle = true;
            }
        } catch (FolderClosedException fex) {
            throw fex;
        } catch (MessagingException mex) {
            supportsIdle = false;
        }
        while (messageListener != null) {
            if (supportsIdle && folder instanceof IMAPFolder) {
                IMAPFolder f = (IMAPFolder) folder;
                f.idle();
            } else {
                // sleep for freq milliseconds
                Thread.sleep(freq);
                // EXISTS notifications.
                if (folder != null && folder.isOpen()) {
                    folder.getMessageCount();
                }
            }
        }
    } catch (Exception ex) {
        Log.error("Error listening new email messages", ex);
    }
}
Also used : MessageCountEvent(javax.mail.event.MessageCountEvent) MessageCountAdapter(javax.mail.event.MessageCountAdapter) IMAPFolder(com.sun.mail.imap.IMAPFolder)

Aggregations

IMAPFolder (com.sun.mail.imap.IMAPFolder)1 MessageCountAdapter (javax.mail.event.MessageCountAdapter)1 MessageCountEvent (javax.mail.event.MessageCountEvent)1