How do I connect to an IMAP server over an SSL connection?

allen petersen

This really isn't documented even in Sun's unsupported com.sun.mail.* packages, now, is it?

Fortunately,you can figure it out by reading the source code for JavaMail. It turns out that Sun's JavaMail implementation uses a SocketFetcher class which can be configured using the Session's properties. Specifically, you can set the following properties:


where <prefix> is your protocol's property prefix, such as 'mail.imap'. To use the JSSE's SSLSocketFactory to connect to your IMAP store, you'll want to set "mail.imap.socketFactory.class" to "javax.net.ssl.SSLSocketFactory".

Here's a sample class that uses these properties. You'll need the JSSE package installed or in your CLASSPATH for this to work. You'll also need to have an SSL enabled IMAP server (or something like sslwrap running) running with trusted certificates. See the JSSE docs for more information.

public class TestSSL {

    public static void main(String[] argv) {
	// configure the jvm to use the jsse security.
	java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
	// create the properties for the Session
	java.util.Properties props = new java.util.Properties();

	// set this session up to use SSL for IMAP connections
	props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
	// don't fallback to normal IMAP connections on failure.
	props.setProperty("mail.imap.socketFactory.fallback", "false");
	// use the simap port for imap/ssl connections.
	props.setProperty("mail.imap.socketFactory.port", "993");

	// note that you can also use the defult imap port (including the
	// port specified by mail.imap.port) for your SSL port configuration.
	// however, specifying mail.imap.socketFactory.port means that,
	// if you decide to use fallback, you can try your SSL connection
	// on the SSL port, and if it fails, you can fallback to the normal
	// IMAP port.
	try {
	    // create the Session
	    javax.mail.Session session = javax.mail.Session.getInstance(props);
	    // and create the store..
	    javax.mail.Store store = session.getStore(new 
	    // and connect.
	    System.out.println("connected to store.");
	} catch (Exception e) {
	    System.out.println("caught exception: " + e);