问题
I came across the IdleManager class and the watch method, which keeps the imap folder open and is in theory watching for new messages, but how do I get it to output or notify when a new email arrives?
The code:
public static void main(String[] args) throws MessagingException, IOException {
IMAPFolder folder = null;
Store store = null;
String subject = null;
Flag flag = null;
try
{
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
props.setProperty("mail.imaps.usesocketchannels", "true");
Session session = Session.getDefaultInstance(props, null);
ExecutorService es = Executors.newCachedThreadPool();
final IdleManager idleManager = new IdleManager(session, es);
store = session.getStore("imaps");
store.connect("<mail>.com","<username>", "<password>");
folder = (IMAPFolder) store.getFolder("INBOX");
if(!folder.isOpen())
folder.open(Folder.READ_ONLY);
folder.addMessageCountListener(new MessageCountAdapter() {
public void messagesAdded(MessageCountEvent ev) {
Folder folder = (Folder)ev.getSource();
Message[] msgs = ev.getMessages();
System.out.println("Folder: " + folder +
" got " + msgs.length + " new messages");
try {
// process new messages
idleManager.watch(folder); // keep watching for new messages
} catch (MessagingException mex) {
// handle exception related to the Folder
}
}
});
idleManager.watch(folder);
Message[] messages = folder.getMessages();
System.out.println("No of Messages : " + folder.getMessageCount());
System.out.println("No of Unread Messages : " + folder.getUnreadMessageCount());
System.out.println(messages.length);
for (int i=0; i < messages.length;i++)
{
System.out.println("*****************************************************************************");
System.out.println("MESSAGE " + (i + 1) + ":");
Message msg = messages[i];
subject = msg.getSubject();
System.out.println("Subject: " + subject);
System.out.println("From: " + msg.getFrom()[0]);
System.out.println("To: "+msg.getAllRecipients()[0]);
}
}
finally
{
if (folder != null && folder.isOpen()) { folder.close(true); }
if (store != null) { store.close(); }
}
}
This code only gets and outputs the messages that were already in the folder, but it doesn't output new incoming emails.
How do I get it to output or notify new incoming emails?
来源:https://stackoverflow.com/questions/60093386/java-email-listener