Unable to send an email using SMTP (Getting javax.mail.MessagingException: Could not convert socket to TLS;)

I resolved this issue by just commenting out the below property

props.put("mail.smtp.starttls.enable", "true"); 

and the code got executed with no errors or warning or simply delete this line from the above source code. It is working like a charm till date.


Commenting-out the property mail.smtp.starttls.enable means you fall back to a default and unsecured connection, which would work only if the remote SMTP host also accepts unsecured transport on port 587 (the port for mail submission versus port 25 for end-delivery or relay operations).

In my context, TLS is compulsory on 587 and any attempt to open a session without TLS yield the SMTP server error response 530 Must issue a STARTTLS command first.

Then setting mail.smtp.starttls.enable to true alone still yield the same error Could not convert socket to TLS but now with a clue: Server is not trusted. Indeed, you must have either a keystore defined in the JVM start properties that would contain a certificate chain ending onto a trusted root certificate, either enforce trust with this extra property: mail.smtp.ssl.trust set to the remote host name.

Configuring the whole stuff in Spring support for javamail for instance (which you can easily map to plain javamail API) requires all of the following:

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="theRemoteSmtpServer" />
<property name="port" value="587" />
<property name="username" value="muUserID" />
<property name="password" value="myPassword" />
<property name="javaMailProperties">
    <props>
        <prop key="mail.smtp.starttls.enable">true</prop>
        <prop key="mail.smtp.ssl.trust">theRemoteSmtpServer</prop>
        <prop key="mail.smtp.auth">true</prop>
    </props>
</property>
</bean>

Make sure your antivirus software is not blocking the application. In my case Avast was blocking me from sending e-mails in a Java SE application.