Search code examples
jakarta-mail

Spring Mail. javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake


I connect to mail server on protocol smtp on port without encryption. I get error

"Mail server connection failed; nested exception is javax.mail.MessagingException: Could not convert socket to TLS;\n  nested exception is:\n\tjavax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake. Failed messages: javax.mail.MessagingException: Could not convert socket to TLS;\n  nested exception is:\n\tjavax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake"

My bean's config

@Bean
public JavaMailSender javaMailService() {
    JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
    javaMailSender.setHost(host);
    javaMailSender.setProtocol(protocol);
    javaMailSender.setUsername(from);
    javaMailSender.setPassword(password);
    javaMailSender.setPort(port);
    javaMailSender.setDefaultEncoding(encoding);
    Properties javaMailProperties = new Properties();
    javaMailProperties.put("mail.smtp.starttls.enable", "true");
    javaMailProperties.put("mail.smtp.auth", "true");
    javaMailProperties.put("mail.transport.protocol", "smtp");
    javaMailProperties.put("mail.debug", "true");
    javaMailProperties.put("mail.smtp.localhost", "127.0.0.1");
    javaMailProperties.put("mail.smtp.ssl.trust", "*");
    System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
    javaMailSender.setJavaMailProperties(javaMailProperties);

    return javaMailSender;
}

I can say one before it worked. What can be wrong?


Solution

  • There may be a disagreement about which TLS versions or cipher suites are supported by both client and server. If you upgraded the JDK, for example, that might've changed. The https.protocols property isn't used by JavaMail, but if you need to set that for other reasons you may need to set the corresponding JavaMail property, e.g., mail.smtp.ssl.protocols.

    You might need to follow the debugging tips in SSLNOTES.txt to find out exactly what's wrong.