JavaMail API – Sending email via Gmail SMTP example
Here are two examples to show you how to use JavaMail API method to send an email via Gmail SMTP server, using both TLS and SSL connection.
To run this example, you need two dependency libraries – javaee.jar and mail.jar, both are bundle in JavaEE SDK.
Outgoing Mail (SMTP) Server requires TLS or SSL: smtp.gmail.com (use authentication) Use Authentication: Yes Port for TLS/STARTTLS: 587 Port for SSL: 465
GMail SMTP detail here – http://mail.google.com/support/bin/answer.py?hl=en&answer=13287
1. JavaMail – GMail via TLS
Send an Email via Gmail SMTP server using TLS connection.
Example updated on 19/03/2012
Thanks inputs from Sumeet Kumar Yadav and vihor. The below example is updated to get rid of the previous “
Thanks inputs from Sumeet Kumar Yadav and vihor. The below example is updated to get rid of the previous “
javax.mail.AuthenticationFailedException” error. It working perfect now.package com.mkyong.common; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendMailTLS { public static void main(String[] args) { final String username = "username@gmail.com"; final String password = "password"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("from-email@gmail.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to-email@gmail.com")); message.setSubject("Testing Subject"); message.setText("Dear Mail Crawler," + "\n\n No spam to my email, please!"); Transport.send(message); System.out.println("Done"); } catch (MessagingException e) { throw new RuntimeException(e); } } }
2. JavaMail – GMail via SSL
Send an Email via Gmail SMTP server using SSL connection.
package com.mkyong.common; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendMailSSL { public static void main(String[] args) { Properties props = new Properties(); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("username","password"); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("from@no-spam.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@no-spam.com")); message.setSubject("Testing Subject"); message.setText("Dear Mail Crawler," + "\n\n No spam to my email, please!"); Transport.send(message); System.out.println("Done"); } catch (MessagingException e) { throw new RuntimeException(e); } } }
java.net.UnknownHostException: smtp.gmail.com
Some hit the
Some hit the
UnknownHostException: smtp.gmail.com, try ping smtp.gmail.com and make sure you got a response (able to access). Often times, your connection may block by your firewall or proxy behind.

1.Receiving mail
2.Attach mail
3.Replay and forwarding
using java
Hi,
if if anyone is using avast antiverus he should dis-activate it .
if any one is using gmail, try the port n° 25 .
good chance for u all.
thanks,i tried before but i failed.after installing avast i succeded.
Thanks for your help Java mail example but with TLS its not working Showing permission denied .Thanks for All java related help like JSF,Hibernate ,Log4j etc.
thank u thank u thank u
Hi,
Can i execute this sample program in IBM Java.?
If not can you tell me how can i make it work in ibm java??
Its very urgent.
Thanks
Shaf
Hey, there, that works fine…but what about sending mail to multiple recipients??? please share that too..
thanks
Can you please suggest, how to get rid of these errors? Am I missing anything?
Exception in thread “main” java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25;
nested exception is:
java.net.ConnectException: Connection timed out: connect
at SendEmail.main(SendEmail.java:47)
Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25;
nested exception is:
java.net.ConnectException: Connection timed out: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1282)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
at javax.mail.Service.connect(Service.java:297)
at javax.mail.Service.connect(Service.java:156)
at javax.mail.Service.connect(Service.java:105)
at javax.mail.Transport.send0(Transport.java:168)
at javax.mail.Transport.send(Transport.java:98)
at SendEmail.main(SendEmail.java:42)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:383)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:245)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:232)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:377)
at java.net.Socket.connect(Socket.java:539)
at java.net.Socket.connect(Socket.java:488)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:232)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1250)
… 7 more
I got the following error,
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.net.ConnectException: connect: Address is invalid on local machine, or port is not valid on remote machine
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1961)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
at javax.mail.Service.connect(Service.java:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at org.bsnl.wll.sendMail.SendMail.mailReport(SendMail.java:55)
at org.bsnl.wll.sendMail.SendMail.prepareMailAndSend(SendMail.java:44)
at org.bsnl.wll.trafficAnalisis.DailyTrafficAnalysis.main(DailyTrafficAnalysis.java:24)
Caused by: java.net.ConnectException: connect: Address is invalid on local machine, or port is not valid on remote machine
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 java.net.Socket.connect(Unknown Source)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:321)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:237)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1927)
I am using a Win 8 machine, java version 1.7.0.17 and java mail 1.4.7
Can you please help
Thanks for neat solution.But
1. Authorization credential should be used for authentication than how come form field “message.setFrom(new InternetAddress(“from.support@gmail.com”));” be different from authentication credentials?Even I kept different credentials in form and authentication,but mail is still sent to the one I mentioned in authentication.What I am missing?
2.If I am to send a mail with no-reply option,how this can be done?
Thanks alot mkyong code works fine…..:)
Its work fine.. thanks alot Mkyong. Thank you very much
It works fine and thanks alot…
Hi
I am really thankful to you for posting this. This is wonderful. However, I have a question.
For SSL, if we use props.put(“mail.smtp.port”, “465″); under a proxy it doesn’t work. Instead, if we use props.put(“mail.smtp.port”, “25″); i.e using port 25 it works fine. What is the difference between these two port numbers and how does proxy affects it?
Thank you.
I have found the problem.
The dependency for javax.mail needs to be the first in the maven build file. I am using spring and scheduler (using a previous example of MKYONG) and somehow these are interfering with the javax.mail dependency.
All working fine now.
hello Sir How do I configure JavaMail to work through my proxy server?
i had configured Java Network Connection in Control Panel, but i doesn’t work. can you help me Sir?
Tried the code above SendMailTLS using my gmail account and got the following error
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
nested exception is:
java.net.SocketException: Permission denied: connect
Any ideas?
I checked my username and password and all works fine when login to gmail account.
try using SSL. It should work
I GET THIS EXCEPTION WHEN TRIED TO EXECUTE THE GIVEN CODE……
IT WORKED FINE IN MY HOME BUT …IN COMPANY I USE A VPN TO CONNECT TO A NETWORK …..WILL THIS HAVE ANY THING TO DO WITH THE EXECEPTION.
Exception in thread “main” java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.net.ConnectException: Connection timed out: connect
at com.igate.mail.SendEmail.main(SendEmail.java:140)
Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.net.ConnectException: Connection timed out: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1934)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:638)
at javax.mail.Service.connect(Service.java:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at com.igate.mail.SendEmail.main(SendEmail.java:134)
Caused by: java.net.ConnectException: Connection timed out: 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 java.net.Socket.connect(Unknown Source)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:288)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:231)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1900)
… 7 more
props.put(“mail.smtp.port”, “25″); instead of props.put(“mail.smtp.port”, “465″);
It didn’t work, i get this exception this time.
Exception in thread “main” java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25;
nested exception is:
java.net.SocketException: Network is unreachable: connect
at com.igate.mail.SendEmail.main(SendEmail.java:136)
Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25;
nested exception is:
java.net.SocketException: Network is unreachable: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1934)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:638)
at javax.mail.Service.connect(Service.java:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at com.igate.mail.SendEmail.main(SendEmail.java:130)
Caused by: java.net.SocketException: Network is unreachable: 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 java.net.Socket.connect(Unknown Source)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:288)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:231)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1900)
… 7 more
HI,
Even i am facing the same problem. did you resolve this?? i get error on both 25 and 465.
Its urgent please help me.
Thanks
Shaff
Thanks for your post. It is very helpful for me :)
I am a great faaaan of you. up till now up to 80% of my issues related to Struts, JavaMail API and Hibernate were resolved by your examples…
Thanks a lot…
nice…it works fine
Thanks for your post…! really helpful
getting this error message while using above code .Use real server address instead of 127.0.0.1 in your account. please post how to resolve this
I have tried your code but it giving me this error can you please help me . i am using websphere 7
javax.mail.MessagingException: Can’t send command to SMTP host;
nested exception is:
javax.net.ssl.SSLHandshakeException: com.ibm.jsse2.util.g: PKIX path building failed: java.security.cert.CertPathBuilderException: PKIXCertPathBuilderImpl could not build a valid CertPath.; internal cause is:
java.security.cert.CertPathValidatorException: The certificate issued by OU=Equifax Secure Certificate Authority, O=Equifax, C=US is not trusted; internal cause is:
java.security.cert.CertPathValidatorException: Certificate chaining error
Sir can u explain the code. It works well. But can’t understand how it works
Thanks for the post Mkyong!! Really helpful.. Even this website http://www.compiletimeerror.com/2013/03/java-mail-api-send-email-from-java-code.html also address something similar.. Have a look.. May help..