javax.mail and plain, STARTTLS, SSL/TSL connection for POP3 and SMTP without keystore

Today my target was to implement various connections for POP3/SMTP email accounts. incuding:

plain connection with no encryption

STARTTLS

SSL/TSL

The key requirement here was to have it without java keystore file configured for storing and accepting server certificates. This should work transparently for the user.

Having dug through tons of not working examples on the net, and after trying figure out some solutions by trial and error, I decided to take my Plain Old Eclipse Debugger and dive into the javax.mail classes. Here are quick results of HOWTO.

The environment you need is Java Mail API 1.4.5 (1.4 doesn’t work properly, due to inability to set custom socket factory for STARTTLS). On the other hand, I don’t use plain SMTP connection, but Spring JavaMailSender, but it has exactly the same config (with properties).

AlwaysTrustSSLContextFactory

First thing to have for encrypted connection is to have SSLContextFactory, that trusts all certificates, to skip the verification stage (this is not required for my application). Here is the code:

The funny part is that the getDefault() static method is crucial here, because javax.mail classes get the SSLContextFactory from this static method, and not by creating the object using constructor. This is a big trap here that can consume a lot of time to conceive. This also can reveal how the rest of sources are written, what is pretty bad for me (strange initializations by static methods and poorly described string properties, with which you can build a lot of combinations to try make it work).

Now, without a lot of complaining more, the revealed solutions. The thing we want to achieve is to get the connected javax.mail.Store from javax.mail.Session to work with POP3, and configured JavaMailSender (with javax.mail properties) for SMTP.

Looking for amount of questions and not working examples on the net, and amount of time I needed to solve it, the guys implemented it this way should get the prize for one of the most obscure solutions in java I was working with.