Java Mail: Session

Kuchi picture Kuchi · Jul 25, 2013 · Viewed 13.2k times · Source

Below the code used to connect and perform operations on an IMAP Folder. So my question is about the javax.mail.Session which in this case would recreate every second (depending on the sleep time and runtime of checkInbox()).

I'm sure that this is not a good solution, especially polling on IMAP is kinda stupid but I couldn't get the IMAP listener running.

Recreating the Session not every run might be a better solution but how do I know when a session is closed or can I close it on purpose? But there is nothing like Session.close() or is the Session than NULL? Or is there some defined timeout on a 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);
}

All in all I have to say it's really hard to find good examples and documentation for javax.mail (besides the API and the FAQ)

Answer

Bill Shannon picture Bill Shannon · Jul 26, 2013

The Session just manages configuration information; there's no need to close it. As long as your configuration doesn't change, you can create the Session once at the beginning and jsut keep using it.

Connections, on the other hand, are expensive and need to be managed carefully by the application. A connection is used for the Store and for every open Folder. A connection can be closed at any time, by the server or due to a network failure. If a connection is not being actively used, you should close it.

Did you find the JavaMail spec and the sample applications on the JavaMail project page? They'll help with a lot of the simple issues, but connection management is a more advanced issue.

Oh, and you can remove all that socket factory stuff and make your application simpler.