Send an email through Gmail in Java

This article shows how to send an email through Gmail in Java.

We use the JavaMail API to send email. You can download the JavaMail API jar from here and the reference implementation jar from here. Or if you are using maven then just add the following dependencies in your pom.xml file.

JavaMail dependencies for Maven

We first define the SMTP properties required to connect to the SMTP server.  Then, we define an SMTP user authenticator that authenticates the sender’s email and password. We, then, create a mail session and construct the email message represented by MimeMessage object. We, then, use the Transport.send() to send the constructed email object.

You can use the example below to send email through any SMTP host and not just Gmail; only thing that would change are the SMTP properties values as applicable to the target SMTP server. Here, we define the properties required to connect to Gmail’s SMTP server.

Output

 


 

0 0 votes
Article Rating
Subscribe
Notify of
guest
1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Preeti
Preeti
7 years ago

Hey,
I’m getting below error on executing the above program.
Sending email…
Problem sending email. Exception : Send failure (javax.mail.AuthenticationFailedException: 454 4.7.0 Too many login attempts, please try again later. k9sm66764999pga.40 – gsmtp
)

Process finished with exit code 0