IMAP client in Java: JavaMail API or Apache Commons Net?
how can i get list of folder as folder instances instead of pure string output?
It looks like apache IMAPClient is a low-level wrapper around the IMAP protocol, so nothing fancier than strings are provided. For an higher level API, you could look into the JavaMail library:
Session session = Session.getDefaultInstance(System.getProperties(),null);
Store store = session.getStore("imaps");
store.connect(this.host, this.userName, this.password);
// Get default folder
Folder folder = store.getDefaultFolder();
// Get any folder by name
Folder[] folderList = folder.list();
Short story : it depends on your real requirements.
If your client is mainly focused on sending and reading mail, the JavaMail API is a de-facto standard high-level API, and it will be much simpler to compose mail, add headers and/or attachements.
On the other hand, if you intend to offer all the possibilities of the IMAP protocol, the lower-level Apache Commons Net library will allow more detailed operations, at the cost of more boiler plate code for simple operations.
Just to complete this answer, you should not forget Apache Commons Email, which according to the home page of the project is built on top of the Java Mail API, which it aims to simplify. It is much closer to JavaMail than to Commons Net.
Without knowing more of what one wants to do, it is hard to give a more precise answer...
There are modern alternatives I recently checked out:
- Yahoo IMAP client: supports async IO using Java Futures, but is low level and maybe too complicated for simple use cases like checking for new mail.
- Email4J: easy-to-use, high-level API that uses Java Mail beneath, but not in Maven central yet and a large PR is still open (I am using the fork)
For local testing, I am using the lightweight docker-imap-devel docker image.
A good introduction, looking behind the scenes of the IMAP protocol (helpful for debugging), can be found at IMAP 101: Manual IMAP Sessions.
Update: In the end, it was the easiest to go with good old javax.mail.imap API and Folder.open()
which worked out of the box, should have checked that earlier…
There's also an experimental IdleManager
that can be used to watch a mailbox for new messages with a supplied ExecutorService
.
Consider looking at Retrieve UnRead Emails from Gmail - JavaMail API + IMAP
It's coded using the JavaMail API, but in my opinion this has a much simpler interface than the Apache commons library.
If you really want to use the Apache commons library, have a look at the javadocs and see what other parameters you can pass to .select()
.