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.
package com.mkyong.common; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; 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) { String host = "smtp.gmail.com"; int port = 587; String username = "username"; String password = "password"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); Session session = Session.getInstance(props); 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 transport = session.getTransport("smtp"); transport.connect(host, port, username, password); 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.
[...] 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 */
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