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 “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 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.

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Oleg
Guest
Oleg

There is solution.
Head over to Account Security Settings (https://www.google.com/settings/security/lesssecureapps) and enable “Access for less secure apps”, this allows you to use the google smtp for clients other than the official ones.

Marcos
Guest
Marcos

It worked for me!

nethra
Guest
nethra

am getting this error:
javax.mail.AuthenticationFailedException: 534-5.7.14 Please log in via your web browser and
534-5.7.14 then try again.
534-5.7.14 Learn more at
534 5.7.14 https://support.google.com/mail/answer/78754 i8sm12193467pao.26 – gsmtp

at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:826)
at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:761)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:685)
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.mail.SendMail.main(SendMail.java:50)

André Smaira
Guest
André Smaira

It doesn’t work for me. It sticks on Transport.send(message). Could someone help me?

Wald
Guest
Wald

Hi…I have java SE, Where may I download javaee.jar and mail.jar? Also the package com.mkyong.common… Thanks a lot..Wald

Damarudhar
Guest
Damarudhar

Exception in thread “main” java.lang.RuntimeException: javax.mail.AuthenticationFailedException: 534-5.7.14 Please log in via your web browser and
534-5.7.14 then try again.
534-5.7.14 Learn more at
534 5.7.14 https://support.google.com/mail/answer/78754 y66sm6467856pfa.54 – gsmtp

at com.jack.javaScrapper.SendMailSSL.main(SendMailSSL.java:44)
Caused by: javax.mail.AuthenticationFailedException: 534-5.7.14 Please log in via your web browser and
534-5.7.14 then try again.
534-5.7.14 Learn more at
534 5.7.14 https://support.google.com/mail/answer/78754 y66sm6467856pfa.54 – gsmtp

at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:809)
at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:752)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:669)
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.jack.javaScrapper.SendMailSSL.main(SendMailSSL.java:39)

manish singh raghav
Guest
manish singh raghav
I am getting following problem and code is not running : javax.mail.MessagingException: Could not convert socket to TLS; nested exception is: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1907) at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:666) 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 module.Mail.main(Mail.java:42) Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at sun.security.ssl.Alerts.getSSLException(Unknown Source) at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source) at sun.security.ssl.Handshaker.fatalSE(Unknown Source) at sun.security.ssl.Handshaker.fatalSE(Unknown Source) at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source) at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source) at sun.security.ssl.Handshaker.processLoop(Unknown Source) at sun.security.ssl.Handshaker.process_record(Unknown Source) at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source) at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown… Read more »
naagsaideep
Guest
naagsaideep

now i am getting same exception in production ….. any Solution for this ??

sary
Guest
sary

make sure to use the latest mail jar file

lastresort
Guest
lastresort

The TLS connection worked like a charm for a long time for me, but now I got a javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first.

The solution was to add props.put(“mail.smtp.EnableSSL.enable”, “true”);

Oleg
Guest
Oleg

I used both version – via TLS and via SSL. Both don’t work!

vik
Guest
vik

javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
nested exception is:
java.net.ConnectException: Connection timed out: connect

i don’t know why..

manivasagam
Guest
manivasagam

Here how can We check invalid email address(dd@notvalidedomain.com) before Transport.send(message); I am facing this issue in my production application. Can you give me some idea!

Damarudhar
Guest
Damarudhar

I am getting this kind of error please help on that

shivam
Guest
shivam

Can’tru showing this error please help me

run:
Exception in thread “main” java.lang.RuntimeException: javax.mail.MessagingException: Could not convert socket to TLS;
nested exception is:
javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
at src.SendMailTLS.main(SendMailTLS.java:54)
Caused by: javax.mail.MessagingException: Could not convert socket to TLS;
nested exception is:
javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1918)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:652)
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 src.SendMailTLS.main(SendMailTLS.java:49)
Caused by: javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:992)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387)
at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:548)
at com.sun.mail.util.SocketFetcher.startTLS(SocketFetcher.java:485)
at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1913)
… 7 more
Caused by: java.io.EOFException: SSL peer shut down incorrectly
at sun.security.ssl.InputRecord.read(InputRecord.java:505)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973)
… 13 more
Java Result: 1
BUILD SUCCESSFUL (total time: 27 seconds)

Gulten
Guest
Gulten

Couldn’t connect to host, port: 127.0.0.1, 25; timeout -1

max
Guest
max

thanks

Tran Vanthach
Guest
Tran Vanthach

Thanks you very much :)

drognisep
Guest
drognisep

This was very helpful as a starting point, but it would be nice if you could show an example of using OAuth to connect to the Google SMTP server as well.

akshay satija
Guest
akshay satija

how to send the link along with the above message please tell

Th?t lòng
Guest
Th?t lòng

I got this error when try to send an email:

javax.mail.MessagingException: Can’t send command to SMTP host;
nested exception is:
javax.net.ssl.SSLHandshakeException: com.ibm.jsse2.util.m: 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 CN=GeoTrust Primary Certification Authority, O=GeoTrust Inc., C=US is not trusted; internal cause is:
java.security.cert.CertPathValidatorException: Certificate chaining error

Plz help me!

Purna chand
Guest
Purna chand

Hi Even i am facing this issue. Which version of JDK you are using

Akash Deep
Guest
Akash Deep

How can I secure my password while using the above method?
As I know, it is not safe to use hard coded password in the app.

Nitin
Guest
Nitin

java.lang.RuntimeException: javax.mail.SendFailedException: Sending failed;
nested exception is:
javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first. r88sm144300941pfe.93 – gsmtp

at Main.sendMail2(Main.java:57)
at Main.main(Main.java:17)
Caused by: javax.mail.SendFailedException: Sending failed;

balakrishna
Guest
balakrishna

Thanks you so much bro
its working

tell me how to send multiple email id’s bro

Batbold Boldbayar
Guest
Batbold Boldbayar

ty

Aditya Jain
Guest
Aditya Jain

hello
if I want to send multiple emails to different users simultaneously, are feasible these options?, because I see creates a new instance for each mail, which would make very slow execution of a program

Jhonny
Guest
Jhonny

Excellent!!! It works for me!! (The second one)

Ultim4t3
Guest
Ultim4t3

can you tell me how to send it to multiple recipients ?

John Mickel Almeñe
Guest
John Mickel Almeñe

thanks a lot sir. works perfectly :)

VENKATREDDY S
Guest
VENKATREDDY S

Simple Example ! Thanks Mkyoung.

Mahmudul Hasan Sujan
Guest
Mahmudul Hasan Sujan
i get this error….please help me… sending failed! Exception in thread “main” java.lang.RuntimeException: javax.mail.SendFailedException: Sending failed; nested exception is: class javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first. z4sm1429241par.6 – gsmtp at javagmailsendexample.Main.main(Main.java:79) Caused by: javax.mail.SendFailedException: Sending failed; nested exception is: class javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first. z4sm1429241par.6 – gsmtp at javax.mail.Transport.send0(Transport.java:218) at javax.mail.Transport.send(Transport.java:80) at javagmailsendexample.Main.main(Main.java:70) Java Result: 1 BUILD SUCCESSFUL (total time: 2 seconds)
Miguel Enriquez
Guest
Miguel Enriquez

The article sound OK, but, you need write more info, same as: Step1, create a Java Class, 2) create a Servlet, 3)….. this article is not for a Begginer. thanks

pooja
Guest
pooja

i’m facing error in “protected PasswordAuthentication getPasswordAuthentication() ” and “PasswordAuthentication(username, password)” for above code gmail via TLS

the errors are

1)String cannot be converted to char[]

return new PasswordAuthentication(username, password);

2)getPasswordAuthentication() in cannot override getPasswordAuthentication() in Authenticator

protected PasswordAuthentication getPasswordAuthentication() {