日期:2014-05-17 浏览次数:20774 次
package com.hp.cloud;
import java.util.*;
import javax.mail.*;
import javax.mail.event.*;
import com.sun.mail.imap.*;
public class Monitor {
public static void main(String[] args) {
// String host = "imap.qq.com";
// String user = "xxxxxxxxx@qq.com";
// String password = "password";
String host = "imap.126.com";
String user = "test@126.com";
String password = "password";
int freq = 5000;
System.out.println("\nTesting monitor\n");
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(host, user, password);
// Open a Folder
Folder folder = store.getFolder("inbox");
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");
}
});
// Check mail once in "freq" MILLIseconds
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;
}
for (;;) {
if (supportsIdle && folder instanceof IMAPFolder) {
IMAPFolder f = (IMAPFolder) folder;
f.idle();
System.out.println("IDLE done");
} else {
Thread.sleep(freq); // sleep for freq milliseconds
// This is to force the IMAP server to send us
// EXISTS notifications.
folder.getMessageCount();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}