Accessing Gmail using the JavaMail API

One of the basic features that I want on Gmail is the option to delete the mails within two selected dates.I am not very sure if that is possible, but the idea really inspired me to get hands on in the JavaMail API. It is very easy to use and configure in your own program in eclipse.

Though I used the JavaMail 1.4.7 for the purpose of testing, you can download the latest from here.

After you have downloaded, create a project and go to Properties->Java Build Path. Click on add external jars and browse the path where the jar file is located. Next is to create a class and inside the main program create a Property list as below;

Properties props = new Properties();

Then depending upon the mailer client we want to access we would put the values. Below I try to access my Gmail, so I have given the values as:

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

props.put("mail.smtp.starttls.enable", "true");

props.put("", "");

props.put("mail.smtp.port", "587");

Once the properties list is set, we would be required to create the Session object using the below code:

String username="";
String password="Password123";
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);

Now the MimeMessage object needs to be created where we set the sender’s email id, receipient email id, subject and text .

message.setFrom(new InternetAddress(""));
message.setSubject("Testing Subject");
+ "\n\n This is a test email!");


Just type the above codes. Run the program and check the gmail inbox. Test mail should be there.
Cheers.. 🙂


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