I am getting the following exception while trying send an email from java via gmail.
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1391)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:412)
at javax.mail.Service.connect(Service.java:288)
at javax.mail.Service.connect(Service.java:169)
at Mail.Send(Mail.java:75)
at Mail.main(Mail.java:85)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
at sun.security.ssl.BaseSSLSocketImpl.connect(Unknown Source)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:233)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1359)
... 5 more
I referred http://www.tutorialspoint.com/javamail_api/javamail_api_gmail_smtp_server.htm and Send email using java but same exception is coming both for SSL and TLS. Any fix for this?
Thanks in advance.
You will need to enable SMTP access in GMAIL, also you need to allow unsecure clients for your account:
https://www.google.com/settings/security/lesssecureapps
https://support.google.com/mail/answer/75726
Be aware that the smtp port you want to use is open in your firewall! I suggest to try a connection check from the machine where your code is running with Thunderbird if possible. Then you know if the client is able to connect.
After you to enable SMTP access in GMAIL, also you need to allow unsecure clients for your account ( as suggested by LucasF) Try this configuration :
Me I use this configuration with import org.springframework.mail.SimpleMailMessage class and it's works.