JavaMail API – Sending email via Gmail SMTP example

email icon

In this article, we will show you how to send an email via Gmail SMTP server.

To send email in Java, we need JavaMail

pom.xml

	<dependency>
		<groupId>com.sun.mail</groupId>
		<artifactId>javax.mail</artifactId>
		<version>1.6.2</version>
	</dependency>

1. Gmail SMTP via TLS


SMTP = smtp.gmail.com 
Port = 587
SendEmailTLS.java

package com.mkyong;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class SendEmailTLS {

    public static void main(String[] args) {

        final String username = "username@gmail.com";
        final String password = "password";

        Properties prop = new Properties();
		prop.put("mail.smtp.host", "smtp.gmail.com");
        prop.put("mail.smtp.port", "587");
        prop.put("mail.smtp.auth", "true");
        prop.put("mail.smtp.starttls.enable", "true"); //TLS
        
        Session session = Session.getInstance(prop,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("from@gmail.com"));
            message.setRecipients(
                    Message.RecipientType.TO,
                    InternetAddress.parse("to_username_a@gmail.com, to_username_b@yahoo.com")
            );
            message.setSubject("Testing Gmail TLS");
            message.setText("Dear Mail Crawler,"
                    + "\n\n Please do not spam my email!");

            Transport.send(message);

            System.out.println("Done");

        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

}

2. Gmail via SSL

2.1 The logic is the same, just pass in different properties values.


SMTP = smtp.gmail.com 
Port = 465
SendEmailSSL.java

package com.mkyong;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class SendEmailSSL {

    public static void main(String[] args) {

        final String username = "username@gmail.com";
        final String password = "password";

        Properties prop = new Properties();
		prop.put("mail.smtp.host", "smtp.gmail.com");
        prop.put("mail.smtp.port", "465");
        prop.put("mail.smtp.auth", "true");
        prop.put("mail.smtp.socketFactory.port", "465");
        prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        
        Session session = Session.getInstance(prop,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("from@gmail.com"));
            message.setRecipients(
                    Message.RecipientType.TO,
                    InternetAddress.parse("to_username_a@gmail.com, to_username_b@yahoo.com")
            );
            message.setSubject("Testing Gmail SSL");
            message.setText("Dear Mail Crawler,"
                    + "\n\n Please do not spam my email!");

            Transport.send(message);

            System.out.println("Done");

        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

}

3. Application-specific password required

3.1 If 2-Step verification is ON. We will hits the following error message :


Caused by: javax.mail.AuthenticationFailedException: 534-5.7.9 Application-specific password required. Learn more at
534 5.7.9  https://support.google.com/mail/?p=InvalidSecondFactor - gsmtp

	at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:965)
	at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:876)
	at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:780)
	at javax.mail.Service.connect(Service.java:388)
	at javax.mail.Service.connect(Service.java:246)
	at javax.mail.Service.connect(Service.java:195)
	at javax.mail.Transport.send0(Transport.java:254)
	at javax.mail.Transport.send(Transport.java:124)
	at com.mkyong.calculator.SendEmail.main(SendEmail.java:41)

3.2 To fix it, follow this guide to create an App Password

URL : https://support.google.com/accounts/answer/185833?p=InvalidSecondFactor

app password

URL : https://myaccount.google.com/security

No difference in code, just puts the newly generated app password instead.

SendEmail.java

package com.mkyong;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class SendEmail {

    public static void main(String[] args) {

        final String username = "username@gmail.com";
        final String password = "puts your app password here"; // update here

		// same code...
    }

}
java.net.UnknownHostException: smtp.gmail.com
Make sure firewall or proxy server didn’t block this smtp.gmail.com

References

About the Author

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

Comments

avatar
294 Comment threads
160 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
330 Comment authors
HemaSagarPabloMichael Coopermahadi Recent comment authors
newest oldest most voted
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?

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.

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

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)

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)

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

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 »

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() {

Jhonny
Guest
Jhonny

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

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”);

Archit Sud
Guest
Archit Sud

Facing issue with the code. It gives below given exception. Please suggest solution for the same :

javax.mail.AuthenticationFailedException
at javax.mail.Service.connect(Service.java:306)
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 com.bullbeardevice.util.MailSender.sendMail(MailSender.java:65)

Gaurav
Guest
Gaurav

Excellent article! I used SSL approach and able to send mail to gmail account. I was stuck in this for some time. Thanks for the help.

Parth
Guest
Parth

SSL worked but TLS did not worked it says the authentication failed so may i know the reason why it say so and thanks for the code it worked after i tried so many codes and each code failed except urs so thank u so much

zrivera
Guest
zrivera

SSL works fine, and is very easier!!! Thanks man!

Cheers!!

phuoc le
Guest
phuoc le

Thank you ! This example is very useful for me.

Exorcist2010
Guest
Exorcist2010

TLS Failed for me? No tuts seem to work for GMail or Windows Live TLS :\

vivek duneja
Guest
vivek duneja

thank you sir this example helped me a lot and is very useful
it complete as you have shown the settings to be done on gmail for this
purpose via link

plz tell what should be done for rediffmail

Peter
Guest
Peter

Very good site thank you for all the content.

Using the above email prog how would I go about adding in the ability to attach a file?

Many thanks,

Peter

yehia
Guest
yehia

thank you sir, but it dose not work witn me and give me this erroe:
Exception in thread “main” java.lang.RuntimeException: javax.mail.AuthenticationFailedException: 535-5.7.1 Username and Password not accepted. Learn more at
535 5.7.1 http://mail.google.com/support/bin/answer.py?answer=14257 g17sm4815100wee.5

at com.mkyong.common.JavaMailAppl2.main(JavaMailAppl2.java:78)
Caused by: javax.mail.AuthenticationFailedException: 535-5.7.1 Username and Password not accepted. Learn more at
535 5.7.1 http://mail.google.com/support/bin/answer.py?answer=14257 g17sm4815100wee.5

at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:648)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:583)
at javax.mail.Service.connect(Service.java:313)
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 com.mkyong.common.JavaMailAppl2.main(JavaMailAppl2.java:57)

and I’m sure from username and password

Santosh
Guest
Santosh

Thank you sir for the code but can u please publish the code for receiving the email.

Adrian Lee
Guest
Adrian Lee

This was extremely useful! I’ve been troubleshooting my code with the API and with examples. Yours solved my problem. Thanks

jansi
Guest
jansi

i need email coding and chating room coding in j2ee

mani
Guest
mani

i am a beginner in java…. can you please tell, how to compile and run this code.

mani
Guest
mani

thank you mkyong;

kindly help me in the following:

i used the following code in a program, but it is showing error;

props.put(“mail.smtp.host”, “mail.yourisp.com”);

can you tell, what is the smtp host for gmail and how to find isp…. please help me…..

trackback
Javamail

[…] is just an API – you need a real "mail agent" for it to talk to. Here's a good link: http://www.mkyong.com/java/javamail-…-smtp-example/ SUGGESTION: 1. Set up a GMail account (for testing purposes) 2. Write the JavaMail "hello […]

Darshan Shroff
Guest
Darshan Shroff

This was the easiest example of all others listed on google and worked in the first shot. Good work.

krubha
Guest
krubha

Sir,i would like to send mail via gmail using JAVAMAIL with JSP…

trackback
ideas para el proyecto « Desarrollo funciones SI
krishnap
Guest
krishnap

Hi Your JavaMailApp2.java works very well and thanks for proving here .
You are great .