Send & Receive emails through a GMail account using Java


All of us have the experience of sending emails using web services such as Google mail,Yahoo mail, Hotmail, …etc. But here I’m going to mention how to send and read emails through a Java desktop application.

You can Send emails, Read emails, Send replies, Add attachments and many more through Java applications. But in here I’m going to mention first two only.

What you need

1. I’m going to do this using NetBeans. So NetBeans is essential.

2. You have to get JavaMail API. You can have it from here.

How to setup JavaMail API

Unzip the downloaded file. Open the NetBeans application. Open Project window and right click on the Libraries. Click on Add JAR/Folder . Select mail.jar file and add it.

How to do it

When you refer internet you can see common ways of sending mails. But there’re some special things to follow when dealing with GMail account. So here is the example that worked for me.

import java.util.*;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.swing.JOptionPane;

 * @author BUDDHIMA

public class GmailClient {

    private String userName;
    private String password;
    private String sendingHost;
    private int sendingPort;
    private String from;
    private String to;
    private String subject;
    private String text;
    private String receivingHost;
//    private int receivingPort;

    public void setAccountDetails(String userName,String password){

        this.userName=userName;//sender's email can also use as User Name


    public void sendGmail(String from, String to, String subject, String text){

         // This will send mail from --> to -->


        // For a Gmail account--sending mails-- host and port shold be as follows


        Properties props = new Properties();

        props.put("", this.sendingHost);
        props.put("mail.smtp.port", String.valueOf(this.sendingPort));
        props.put("mail.smtp.user", this.userName);
        props.put("mail.smtp.password", this.password);

        props.put("mail.smtp.auth", "true");

	     Session session1 = Session.getDefaultInstance(props);

	     Message simpleMessage = new MimeMessage(session1);

        //MIME stands for Multipurpose Internet Mail Extensions

		InternetAddress fromAddress = null;
		InternetAddress toAddress = null;

		try {

			fromAddress = new InternetAddress(this.from);
			toAddress = new InternetAddress(;

		} catch (AddressException e) {


                       JOptionPane.showMessageDialog(null, "Sending email to: " + to + " failed !!!", "Falied to Send!!!", JOptionPane.ERROR_MESSAGE);


		try {


			simpleMessage.setRecipient(RecipientType.TO, toAddress);

                        // to add CC or BCC use
                        // simpleMessage.setRecipient(RecipientType.CC, new InternetAddress(""));
                        // simpleMessage.setRecipient(RecipientType.BCC, new InternetAddress(""));



        //sometimes Transport.send(simpleMessage); is used, but for gmail it's different

            Transport transport = session1.getTransport("smtps");

            transport.connect (this.sendingHost,sendingPort, this.userName, this.password);

            transport.sendMessage(simpleMessage, simpleMessage.getAllRecipients());


            JOptionPane.showMessageDialog(null, "Mail sent successfully ...","Mail sent",JOptionPane.PLAIN_MESSAGE);

		} catch (MessagingException e) {


                       JOptionPane.showMessageDialog(null, "Sending email to: " + to + " failed !!!", "Falied to Send!!!", JOptionPane.ERROR_MESSAGE);



    public void readGmail(){

        /*this will print subject of all messages in the inbox of*/

        this.receivingHost="";//for imap protocol

        Properties props2=System.getProperties();

        props2.setProperty("", "imaps");
        // I used imaps protocol here

        Session session2=Session.getDefaultInstance(props2, null);

            try {

                    Store store=session2.getStore("imaps");

                    store.connect(this.receivingHost,this.userName, this.password);

                    Folder folder=store.getFolder("INBOX");//get inbox

          ;//open folder only to read

                    Message message[]=folder.getMessages();

                    for(int i=0;i<message.length;i++){

                        //print subjects of all mails in the inbox


                        //anything else you want


                    //close connections



            } catch (Exception e) {




    public static void main(String[] args) {

        String mailFrom=new String("");

        //Sender must be a Gmail Account holder

        String mailTo=new String("");

        //but here you can send to any type of mail account

        String senderPassword=new String("1234");

        String senderUserName=new String("sender");

        //Mention your email subject and content

        String mailSubject=new String("Testing Mail");

        String mailText=new String("Have an Nice Day ...........!!!");

        //Create a GmailClient object

        GmailClient newGmailClient=new GmailClient();

        //Setting up account details

        newGmailClient.setAccountDetails(senderUserName, senderPassword);

        //Send mail

        newGmailClient.sendGmail(mailFrom, mailTo, mailSubject, mailText);

        //Receive mails




What’s more

Using JavaMail API you can send/receive mails using other email services such as Yahoo, Hotmail, … etc. or your own mail server !

But you have to set the appropriate host and port numbers.

For setting up your own mail server use JAMES.


I’ve found that there’s a special API only for GMail accounts (g4j). But in here I used the method which can be used with any other email services.


If you are more interested in this, following resources would be helpful.




Improve your application by adding emailing capability !!!


22 thoughts on “Send & Receive emails through a GMail account using Java

  1. Hi,
    I’m doing an Open Univeristy project for my BSc. I’m implementing the iCalendar structure in Java. One part of my project is an email client. I have found your code, and with your permission – I would like to use it in my project.
    Great job by the way. Nice, simple, clean, and working well.


  2. I tried to do code but the follow exception faced me
    javax.mail.MessagingException: Unknown SMTP host:;

    any help …..

    1. For your case these links may be helpful:
      – Insert an authenticator
      – Google support page
      If you can find a solution, please mention it here. As I haven’t faced with such a case with this code, your feedback would be useful to others as well. 🙂

  3. yeah… Its working finally… but I had a firewall problem. When I deactivate my antivirus program it was worked…. 😀 thank you sooo much….

  4. getting the following error

    HTTP Status 500 – Class GmailClient is not a Servlet

    type Exception report

    message Class GmailClient is not a Servlet

    description The server encountered an internal error that prevented it from fulfilling this request.


    javax.servlet.ServletException: Class GmailClient is not a Servlet
    root cause

    java.lang.ClassCastException: GmailClient cannot be cast to javax.servlet.Servlet

    please help
    thanks in advance

  5. thanx u so much i was facing some issues to fetch emails using gmail server but program is really good thanx again

  6. Hi
    your work is really appreciated
    just one question… I need to get the sender email address, but, when I print the getFrom() of the message i get this:
    can you please help me?

  7. Getting the following error:
    javax.mail.MessagingException: Could not connect to SMTP host:, port: 465;
    Caused by: Connection refused: connect

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s