Testing SSL Java web apps with mails

The guide How to configure SSL on the Jetty wiki guides you through creating a self-signed certificate, required for developing and testing Java web applications that require SSL. The guide works fine, but causes a hard-to-debug side effect.

By creating your own keystore, you exclude the default list of trusted certificates. This is a problem when using trying to send mail to a SMTP server with a signed certificate, as that now isn’t trusted anymore. Specifically, the following exception is thrown when trying to connect to the smtp server:

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

To fix this, you have to import the certificate of the server you’re trying to connect to into your custom keystore. The InstallCert program is the right tool for that.

In my case, I copied the keystore file into my project root, named “jssecacerts”, and ran “java InstallCert smpt.gmail.com:465 password” (“password” is the passphrase as defined when creating the keystore). InstallCert then updates the “jssecacerts” file – now is includes my own self-signed certificate, as well as the Google one. I copied that back to where Jetty could find it, replacing the old keystore file.

Btw., to configure Spring’s JavaMailSenderImpl to use GMail as the SMTP Server:

public @Bean JavaMailSender mailSender() {
	JavaMailSenderImpl sender = new JavaMailSenderImpl();
	sender.setPort(465);
	sender.setProtocol("smtps");
	sender.setHost("smtp.gmail.com");
	sender.setUsername("[email protected]");
	sender.setPassword("your-password");
	return sender;
}

I hope this helps someone else to solve this problem in less time then I spend on it.

-Jörn