javaspring-bootmavenemailsmtp

Spring Boot - Java Mail - Couldn't connect to host


I've implemented the email manager using JavaMailSender into my Java application, configured with Gmail email, and locally tested.

I'm using a free domain by freenom.

in localhost on my pc everything working perfectly. But deploying on the server the application obtains this error:

c.m.a.m.components.EmailManager          : sendRegisterEmail Exception: Mail server connection failed; 
nested exception is com.sun.mail.util.MailConnectException: 
Couldn't connect to host, port: smtp.gmail.com, 587; timeout -1;
  nested exception is:
        java.net.UnknownHostException: smtp.gmail.com. Failed messages: 
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 587; timeout -1;
  nested exception is:
        java.net.UnknownHostException: smtp.gmail.com

test done

application.properties

spring.mail.host=smtp.gmail.com
spring.mail.port=587

spring.mail.username=***********@gmail.com
spring.mail.password=***********

spring.mail.properties.mail.debug=false

spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

spring.mail.mime.charset=UTF-8
spring.mail.transport.protocol=smtp

Solution

  • Try to change spring.mail.port to 465. This might help.

    Port 587 is technically correct. However, many ESPs have adopted implicit TLS on port 465. Also, there's probably a firewall preventing you from connecting directly, you may need to connect through a proxy.