Showing posts with label gmail. Show all posts
Showing posts with label gmail. Show all posts

Tuesday, August 23, 2022

Mail Sending Issue in Java Application

Sometimes while sending the mail in the java application we might get the following issue.

org.springframework.mail.MailSendException: Mail server connection failed; nested exception is com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 465; timeout -1;
  nested exception is:
	java.net.ConnectException: Connection timed out (Connection timed out). Failed messages: com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 465; timeout -1;
  nested exception is:
	java.net.ConnectException: Connection timed out (Connection timed out)
	at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:432)
	at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:345)
	at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:340)
	at org.springframework.mail.javamail.JavaMailSender$send$0.call(Unknown Source)
	at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
	at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
	at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
	at grails.plugins.mail.MailMessageBuilder.sendMessage(MailMessageBuilder.groovy:130)
	Caused by: com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 465; timeout -1
Caused by: java.net.ConnectException: Connection timed out (Connection timed out)

This might be due to a different reason.

Due to Firewall setup:

While sending mail we are using ports like 465 or 587 or other ports. So if you enable the firewall rules on your server then we might get this issue. So, enable the firewall rules for those TCP ports for outbound in your firewall settings.

The service provider disabled the port:

For security reasons, some server service providers disable those ports. For e.g:

For this, contact the service provider to allow the port or change the port on your configuration for your application. In the java application, for Gmail smtp.gmail.com we can use 587 instead of 465. The SMTP configuration looks as below:

["mail.smtp.host"           : "smtp.gmail.com",
				 "mail.smtp.starttls.enable": "true",
				 "mail.smtp.auth"           : "true",
				 "mail.smtp.port"           : "587",
		]
Share: