I'm trying to connect to a mail server which uses StartTLS with a self signed certificate via Java mail API. And that seems to be a problem, because i can't find any way to set accepted certificates or a truststore for StartTLS.
Properties props = new Properties();
props.put("mail.imap.starttls.enable", "true");
props.put("mail.imap.starttls.required", "true");
Session session = Session.getInstance(props);
Store store = session.getStore("imap");
store.connect(hostName, port, userName, userPassword);
When i run my application as is, i get this PKIX path error:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
I would prefer not to use VM parameters like "-Djavax.net.ssl.trustStore"
because i want to be able to control trusted certificates per access.
Sidenote: I've seen people use "mail.imap.socketFactory.class"
to set their own implementation of SocketFactory
with a self defined TrustManager
.
But when i do that my connection fails with
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
I think this is because setting the socket factory will actually use SMTP over SSL instead of StartTLS (which starts as a plain text connection and switches to TLS later).
mail.smtp.ssl.trust
property to the name of the host you want to trust. Or, you can use the InstallCert program to load your self-signed certificate from the server into your default trust store. – Thistle