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.
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); } } }
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.






will i be able to send mail through esmtp server using same above code.
what is the difference b/w ssl and Tsl connection?
I am getting the following errors, HELP plz…
Exception in thread “main” java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.smtp.test.SendMailTLS.main(SendMailTLS.java:48)
Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1972)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:642)
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.smtp.test.SendMailTLS.main(SendMailTLS.java:43)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(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:319)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:233)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1938)
… 7 more
Thanks so much, it worked with out any issue..Great and crispy example :)..
thanks it works fine,but how to atach file .
Hi MKyong,
I am getting follwoing error message when i try to send an email.
javax.mail.SendFailedException: Sending failed;
nested exception is:
class javax.mail.MessagingException: Exception reading response;
nested exception is:
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
I am getting this error when i use my customer’s SMTP server information (using port 25). When i use smtp.gmail.com, it is working.
Please let me know your suggestion.
Thank you!
Murugesan
i dont know why but it doesn’t work if I am using proxy to connect internet otherwise it works great…………
MKyong,
I am getting follwoing error message when i try to send an email.
javax.mail.SendFailedException: Sending failed;
nested exception is:
class javax.mail.MessagingException: Exception reading response;
nested exception is:
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
I am getting this error when i use my customer’s SMTP server information (using port 25). When i use smtp.gmail.com, it is working.
Please let me know your suggestion.
Thank you!
Murugesan
Oops, meant SSL
Hi, im getting the;
java.net.ConnectException: Connection refused: connect
im trying the smtp example.
JavaMail – GMail via SSL
am getting following error
javax.mail.AuthenticationFailedException: 535-5.7.1 Please log in with your web browser and then try again. Learn more at 535 5.7.1 https://support.google.com/mail/bin/answer.py?answer=78754 b7sm6332724pba.2
please help me
I am also getting the same error.I took the above code only and had not changed anything.
Thanks. TLS is working. confirmed :)
work fine. Thanks.
What to set for the username and password…
Do reply me!!
Thanks..
Sorry, don’t get you.
Username will be your (Gmail) email address, while the password your Gmail password.
Source: The Google support link found at the beginning of the post (http://mail.google.com/support/bin/answer.py?hl=en&answer=13287).
Anyway, thanks mkyong, your code worked perfectly. Had an hour of frustration trying to figure out how to do this before I found you code. :)
thanks
its unable to generate the certificate..i’m using RAD 8.0.3
please clear me
Exception in thread “main” java.lang.RuntimeException: javax.mail.AuthenticationFailedException: failed to connect
at mypack.SendMailTls.main(SendMailTls.java:50)
Caused by: javax.mail.AuthenticationFailedException: failed to connect
at javax.mail.Service.connect(Service.java:322)
at javax.mail.Service.connect(Service.java:172)
at javax.mail.Service.connect(Service.java:121)
at javax.mail.Transport.send0(Transport.java:190)
at javax.mail.Transport.send(Transport.java:120)
at mypack.SendMailTls.main(SendMailTls.java:45)
this error is generated why are error coming in sendmail program i am using eclipse helios please consider me next following step ervaibhav78@gmail.com
Thanks for article. !
A good little example.
thx
Thnks a lot for this article.
I have juste 1 question how i get the password and username for authentification ? i would install server smtp in my machine localhost or juste using the librairie ? thanks.
Thx for the code!
Hey there!!
thanx for the code..i tried for “JavaMail – GMail via SSL”…m getting no error…bt at the same time…m nt getting any output..i.e mail..
plz help..
thanx
Your are so great MAN!
Thank you very much
[...] http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/ Like this:LikeBe the first to like this post. [...]
Hi!
I’m trying to use the URLDataSource. For some reason i cannot attach the image. I’m behind a proxy but i haven’t tried somewhere else. Can you tell me what’s wrong?
Thanks in advance!
javax.mail.MessagingException: IOException while sending message;
nested exception is:
java.net.ConnectException: Connection timed out: connect
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1141)
at EnviarMail.enviaCorreoElectronico(EnviarMail.java:121)
at EnviarMail.main(EnviarMail.java:59)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(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 sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at javax.activation.URLDataSource.getInputStream(Unknown Source)
at javax.activation.DataHandler.writeTo(Unknown Source)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1476)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:865)
at javax.mail.internet.MimeMultipart.writeTo(MimeMultipart.java:462)
at com.sun.mail.handlers.multipart_mixed.writeTo(multipart_mixed.java:103)
at javax.activation.ObjectDataContentHandler.writeTo(Unknown Source)
at javax.activation.DataHandler.writeTo(Unknown Source)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1476)
at javax.mail.internet.MimeMessage.writeTo(MimeMessage.java:1772)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1099)
… 2 more
my code:
Thanks vihor. I’ve been trying to get this working for a while and you’re code nailed it. Thanks.
Thanks a lot. It worked like charm.
Great Work
Thanks and Warm Regards,
Irfan
if your code is correct , email id and password is also correct.
and your getting google authentication exceptition.
then open gmail using web browser enter username & password
then gmail will ask for word verification. after word verfication you will login into account.
then run you java code…no google authentication exceptition will come
Thanks, this code works fine
Hi all,
and thanks for the hints.
However, I have a little problem;
I’m trying example ‘JavaMail – GMail via TLS’
and I can say it basically ‘works’.
However, what I am finding, and perhaps I misunderstand the goal here, is that gmail hijacks my ‘from’ field.
My goal, or intention, is to simply use gmail as a smtp relay, to send on email from my own email server, which existing on a dynamic IP range, has troubles being accepted out there in the spam jittery world.
The actual wanted results being that email sent on, be identified as having come from :
me@myserver.org
and not,
@gmail.com
Yet, this is what happens.
Any ideas? What are others experience?
Oh, and I forgot to mention;
I have tried almost the exact same thing with my own ISP smtp server, and things come out as hoped/expected.
/* TLS also need authentication,you have to give authentication in your session value */
Your program is giving javax.mail.MessagingException: Could not convert socket to TLS;
please hint for solve it.
thanks in Advance.
SSL worked but the TLS sample failed with this:
Exception in thread “main” java.lang.RuntimeException: javax.mail.AuthenticationFailedException: failed to connect, no password specified?
The password is specified but no joy. Pls advise. Thanks.
The original code is badly written. When the Transport.send is being called the authentication might still not be completed, that’s probably why you got the error. One should add ConnectionListener to the transport object and then call Transport.send when the connection is fully opened which means putting the call inside the ‘opened’ event handler of the ConnectionListener object.
Well, I must correct myself. I tried both, the original version and mine. Neither works. However, I found extremely strange that it worked for other users here. Javadoc API for Transport.send says:
“Note that send is a static method that creates and manages its own connection. Any connection associated with any Transport instance used to invoke this method is ignored and not used.”
So, transport.connect(host, port, username, password) is actually irrelevant and is not used at all during the invocation of Transport.send. Having in mind that, I managed to construct the following working version:
I tried using the script it says no password specified… which username and passowr dis it pertaining to? where do we register? tnx
Help a lot
Thank you !!
I have the same exception as you. I tested this piece of code at home and it worlkd OK. Then I tried it at my work place and I got the exception (ping also times out).
So I guess it may have something to do with the internal proxies or conf features oin my company’s intranet. Checking with my IT services.
Any help will be welcome.
thanks, i’ve been looking for this in a lot of sites, and your code is the only, that i found that works!
sir i cannot add multiple recipients in sendmailtls as said by comment(in program).whenever i separate them by cooma i get an error
Amit,
First, you’re an idiot…
Second, post the actual error you’re whining about!
Third, read the JavaDoc…
message.addRecipient(RecipientType.TO, new InternetAddress(“amit@plonker.com”));
message.addRecipient(RecipientType.TO, new InternetAddress(“amit2@plonker.com”));
message.addRecipient(RecipientType.TO, new InternetAddress(“amit3@plonker.com”));
i am getting following error
i used my own username and password
Caught: java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.net.ConnectException: Connection refused: connect
java.lang.RuntimeException: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.net.ConnectException: Connection refused: connect
at Groovy.EMail.main(EMail.groovy:45)
Caused by: 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:1706)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:525)
at Groovy.EMail.main(EMail.groovy:40)
Caused by: java.net.ConnectException: Connection refused: connect
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:284)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:227)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1672)
… 2 more