title: Using Java Mail StartTLS with a Truststore
body: <p>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.</p>
  
  <pre><code>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);
  </code></pre>
  
  <p>When i run my application as is, i get this PKIX path error:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>I would prefer not to use VM parameters like <code>"-Djavax.net.ssl.trustStore"</code> because i want to be able to control trusted certificates per access.</p>
  
  <p>Sidenote: I've seen people use <code>"mail.imap.socketFactory.class"</code> to set their own implementation of <code>SocketFactory</code> with a self defined <code>TrustManager</code>.
  But when i do that my connection fails with </p>
  
  <pre><code>javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
  </code></pre>
  
  <p>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).</p>