Java Mail: Session

Below is the code that is used to connect and perform operations in the IMAP folder. So my question is about javax.mail.Session , which in this case will recreate every second (depending on the sleep time and checkinbox () execution time).

I am sure this is not a good solution, especially an IMAP poll looks silly, but I could not start an IMAP listener .

Recreating a session not every start may be the best solution, but how do I know when session is closed , or can I close it on purpose? But is there nothing like Session.close() or is it a session than NULL? Or is there a specific timeout on the session ...

Source :

 final String port = "993"; Properties prop = new Properties(); // I assume there is some redundancy here but this didn't cause any problems so far prop.setProperty("mail.imaps.starttls.enable", "true"); prop.setProperty("mail.imaps.port", port); /** This part can be removed * prop.setProperty("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); * prop.setProperty("mail.imaps.socketFactory.port", port); * prop.setProperty("mail.imaps.socketFactory.fallback", "false"); */ prop.setProperty("mail.imap.ssl.enable", "true"); prop.setProperty("mail.debug", "false"); // Create a session before you loop since the configuration doesn't change Session session = Session.getInstance(prop); // Nearly loop forever in Prod while(true){ // Check the INBOX and do some other stuff Store store = session.getStore("imaps"); store.connect(host, user, pw); // ... the operations on the session ... store.close(); // Sleep a bit try & catch removed Thread.sleep(1000); } 

In general, I have to say that it is very difficult to find good examples and documentation for javax.mail (besides API and FAQ )

+8
java email imap javamail
source share
1 answer

The session only manages configuration information; no need to close it. Until your configuration changes, you can create a session once at the beginning and jsut continue to use it.

Compounds, on the other hand, are expensive and must be carefully handled by the application. The connection is used for the Store and for each open Folder. The connection may be closed at any time, by the server or due to a network failure. If the connection is not actively used, it should be closed.

Did you find the JavaMail specification and sample applications on the JavaMail project page? They will help with many simple problems, but connection management is a more complex problem.

Oh, and you can remove all the contents of this factory socket and make your application simpler.

+10
source share

All Articles