I have a requirement as a part of which i want to read incoming emails from outlook and then do some processing.I am using JavaMail API along with IMAP protocol to implement this.I have written a java class which reads email on messagesAdded event.
Its perfectly working fine with below code in single server environment, but when i deploy it to production where we have 2 servers i end up processing each email twice since the same code is deployed on both the servers,both try to read email once its received in the mailbox.
Below is the code snippet i am using to connect to mailbox and read emails:
try {
Properties props = System.getProperties();
// Get a Session object
Session session = Session.getInstance(props, null);
// session.setDebug(true);
// Get a Store object
Store store = session.getStore("imap");
// Connect
store.connect(argv[0], argv[1], argv[2]);
// Open a Folder
Folder folder = store.getFolder(argv[3]);
if (folder == null || !folder.exists()) {
System.out.println("Invalid folder");
System.exit(1);
}
folder.open(Folder.READ_WRITE);
// Add messageCountListener to listen for new messages
folder.addMessageCountListener(new MessageCountAdapter() {
public void messagesAdded(MessageCountEvent ev) {
Message[] msgs = ev.getMessages();
System.out.println("Got " + msgs.length + " new messages");
// Process incoming mail.
} catch (Exception ex) {
ex.printStackTrace();
}
Any suggestions on how should i restrict an email to be processed only once in multi server environment ?