Core Java

Send Email with Gmail in Java Example

In this example we will see JavaMail API method to send an email via Gmail SMTP server.

The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications. Java Mail API Jar can be included in the maven project by adding the following dependency in pom.xml.

 
 
 
 

1. Add dependency in POM

   <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4</version>
   </dependency>

Now, In order to send mail we need an smtp server, for this we will make use of gmail SMTP Server. The server details can be looked here.

Gmail SMPT provides 2 methods of authentication for sending mails : TLS (The Transport Layer Security) and SSL (Secure Sockets Layer).

We will use the following configuration of each of the protocols :

Port for TLS/STARTTLS: 587
Port for SSL: 465

Now, Lets see both the examples one by one.

2. Send mail using TLS Authentication

JavaGmailSendExample.java

package com.jcg.example;


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

/**
 * Created by anirudh on 28/10/14.
 */
public class JavaGmailSendExample {

    public static void main(String args[]) {

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

        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("yourmail@gmail.com"));
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse("test@gmail.com"));
            message.setSubject("Test JCG Example");
            message.setText("Hi," +
                    "This is a Test mail for JCG Example!");

            Transport.send(message);

            System.out.println("Mail sent succesfully!");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }

}

In the above program we used the javax.mail.Message method to create a message and javax.mail.Transport.send() method to send it.

Now lets see the same example using SSL authentication:

3. Send Mail using Gmail SSL

JavaGmailSSLExample.java

package com.jcg.example;

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

/**
 * Created by anirudh on 28/10/14.
 */
public class JavaGmailSSLExample {

    public static void main(String[] args) {

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

        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("yourmail@gmail.com"));
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse("test@gmail.com"));
            message.setSubject("Test JCG Example");
            message.setText("Hi," +
                    "This is a Test mail for JCG Example!");

            Transport.send(message);

            System.out.println("Mail sent succesfully!");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}

Download Source Code

So, In this example we saw how we can send emails using Gmail and Java Mail API in Java.

Download
You can download the full source code of this example here : JavaGmailSendExample.zip

Anirudh Bhatnagar

Anirudh is a Java programmer with extensive experience in building Java/J2EE applications. He has always been fascinated by the new technologies and emerging trends in software development. He has been involved in propagating these changes and new technologies in his projects. He is an avid blogger and agile enthusiast who believes in writing clean and well tested code.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button