Sunday, April 27, 2014

Simple Java application to read mails

In this post I want to do something about Java mail API. This provides so many classes and methods. There is a simple program to connect to your mailbox and read mails using your mail address and the password. This program is very simple to understand even though it is too long. Try to understand one by one. 

import java.util.*;
import javax.mail.*;

public class ReadMail {
    public ReadMail() {
            Scanner scn = new Scanner(;
            //Section 1
            System.out.print("Enter username : ");
            String userName = scn.nextLine();
            int fpart = userName.indexOf("@");
            int lpart = userName.indexOf(".com");
            String host = userName.substring(fpart, lpart);
            //Section 2
            System.out.print("Enter password : ");
            String password = scn.nextLine();

            //Section 3
            Properties prop = new Properties();
            Session mailSession = Session.getDefaultInstance(prop);
            Store mailStore = mailSession.getStore("pop3s");

            //Section 4
            if("@hotmail".equalsIgnoreCase(host) || "@live".equalsIgnoreCase(host)){
                mailStore.connect("", userName, password);
            else if("@gmail".equalsIgnoreCase(host)){
                mailStore.connect("", userName, password);
            else if("@yahoo".equalsIgnoreCase(host)){
                mailStore.connect("", userName, password);
                System.out.println("We cannot access to your mail provider");

            //Section 5
            Folder mailFolder = mailStore.getFolder("INBOX");
            BufferedReader mailReader = new BufferedReader(new InputStreamReader(;
            Message msg[] = mailFolder.getMessages();

            //Section 6
            for (int i = 1, j=msg.length; i < j ; i++) {
                System.out.println("Message No : " + i ) ;
                System.out.println("From : " + msg[i].getFrom()[0]);
                System.out.println("Subject : " + msg[i].getSubject());
                System.out.println("Date : " + msg[i].getSentDate());
                System.out.println("Content : " + msg[i].getContent().toString());
                //Section 7
                System.out.println("\nDo you want to continue reading ? [Yes or No]");
                String userIn = mailReader.readLine();

                else if("no".equalsIgnoreCase(userIn)){
                    System.out.println("wrong entry");
            //Section 8
            //Section 9
            }catch(NoSuchProviderException e){
                System.out.println("Please check your provider");
            catch(AuthenticationFailedException e){
                System.out.println("Please check your login details");
            catch(Exception e){
    //Section 10
    public static void main(String args[]) throws Exception{
        new ReadMail();

First of all you have to get the Javamail APIDownload from here. If you are using old Java version (below Java 6) you need to download the latest Java Activation Framework (JAF)Download from here. Then you can add them like you did in previous posts (Adding MYSQL JDBC Driver). In this program, you have to import Javax.mail.* package. I have divided this program into 10 sections to get understand easily.

  • Section 1 : Get the mail address and check the host (live/hotmail,gmail,yahoo)
  • Section 2 : Get the password of your mail address
  • Section 3 : Create Property, Store and Session objects
  • Section 4 : Connect to relevant host using username and password
  • Section 5 : Connect to inbox and get messages to Message type array
  • Section 6 : Print the message, subject, from and other details
  • Section 7 : Asking from user to continue the process or terminate
  • Section 8 : Close the Folder and Store objects
  • Section 9 : Exception handling with catch ladder 
  • Section 10 : Create the main method to execute the program
Now you have very simple idea how whole program is going. Then I am going to explain special methods that I have used in this program.

indexOf() , subString()

You can get an idea about these methods using this link of my previous post about String class.

Property class

  • This is not belongs to javax.mail package. 
  • This is a subclass of Hashtable and this is used to maintain a list of values. 

Session class

  • This is the class that enables you to create sessions while sending and receiving mails.
  • This class use the instances of Property class to retrieve information such as port, username, password...etc.  
  • In this program I have used default session using getDefaultInstance() method.

Store class

  • This class helps you to store and retrieve mails from the mail server.
  • getStore() method returns the store for the specified protocol. In my program I have used "pop3s". 

Folder class

  • This class represent a folder for mails.
  • Folder object consist of messages and sub folders.
  • getFolder() method can be used to select the specific folder. You can type the folder name as a parameter. It will return the specified folder.
  • Then you can use open() method to open that folder.
  • In this method you can see something READ_ONLY. It allows you only to read the folder.

Message class

  • Then I have created a mailReader object to read mails from the inbox.
  • Then I have created msg; a Message object to get the messages from mailFolder using getMessages() method.

Section 5

  • getFrom() : get the sender of relevant message
  • getSubject() : get the subject
  • getSentDate() : get the sent date
  • getContent() : get the content of the message

In this program you cannot see the real content of mails. In Gmail and Hotmail you will be able to a message like "javax.mail.internet.MimeMultipart@2c2166f2". If you are using Yahoo you can see some codes like HTML(web content). You know that email are not only consist of text. There are images and other parts. In my next post I will make you another code to identify these things in Java mail.

At last I have closed mailFolder() and mailStore() to prevent resource leak. In this program I have explained only the main points of Java mail API. There are so many classes and methods that can be used to advanced and simplified your programs. 
Hope you enjoy...

Friday, April 11, 2014

How to Insert, Update and Delete data with MySQL database

In my previous post I showed how to connect with MySQL database and retrieve using Java. In this post I am going to illustrate how to insert data into your MySQL database, how to update data on it and how to delete data from it. To do this we use "Prepared Statements" in Java. 

First of all I wanted to create MySQL database and a table in it. Following query will create a database called "test" and a table called "student". If you want to remind about that, try this (

create database test;

use test;

create table student(

 id int primary key,
 name varchar(30),
 age int,
 city varchar(20)

insert into student values

select * from student

Now you have successfully created a "student" table in a database called "test".

Then lets move to the program. You can use your existing project folder or you can create new project also. But don't forget to add the MYSQL JDBC Driver to your project. In previous post you got experience how to add the library into your project. you can find more on,

Here is the simple code of my project. 

package j2ee;

import java.sql.*;

public class DbUpdate {
    public static void main(String[] args) throws SQLException {
        Connection dbConnection = null;
        PreparedStatement PSInsert = null;
        PreparedStatement PSUpdate = null;
        PreparedStatement PSDelete = null;
        String insertTable = "INSERT INTO student" + "(id,name,age,city)VALUES" + "(? , ? , ? , ?)";
        String updateTable = "UPDATE student SET name = ?" + "WHERE id = ?";
        String deleteTable = "DELETE FROM student " + "WHERE id = ?";
            dbConnection  = getDBConnection();
            //for insert
            PSInsert = dbConnection.prepareStatement(insertTable);
            PSInsert.setString(1, "05");
            PSInsert.setString(2, "Sean");
            PSInsert.setString(3, "26");
            PSInsert.setString(4, "Colombo");
            //for update
            PSUpdate = dbConnection.prepareStatement(updateTable);
            PSUpdate.setString(1, "Ann-updated");
            PSUpdate.setString(2, "02");
            //for delete
            PSDelete = dbConnection.prepareStatement(deleteTable);
            PSDelete.setString(1, "04");
        }catch(SQLException e){
            System.out.println("Error occured " + e.toString());
            if(PSInsert !=null){
            if(PSUpdate != null){
            if(dbConnection != null){
    private static Connection getDBConnection(){
        Connection con = null;
        }catch(ClassNotFoundException e){
            System.out.println("Error 1 : " + e.getMessage());
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","1234");
        }catch(SQLException e){
            System.out.println("Error 2 : " + e.getMessage());
        return con;

This is very simple static Java program that can be used to insert, update and delete data from MySQL database. 


    • In this program we retrieve data in run time. So we need to use runtime parameters to perform the task.
    • In my first program in last post I have used Statement objects. We cannot use these objects to retrieve data in runtime. 
    • That is why we use PreparedStatements as runtime objects. This allows to pass runtime parameters to SQL queries.
    • In this program I have created three types of PreparedStatement objects. 

    getDBConnection() method

    • This is not a pre defined method. I have created this method to Connect MySQL database. 
    • I have used separate try-catch blocks to easily identify any errors that can be happen while connecting.

    setAutoCommit() or commit() 

    • This commit keyword belongs to SQL transactions. 
    • commit is used to save the changes in the SQL. 
    • In JavaSE 7 API, it says, void commit() Makes all changes made since the previous commit / rollback permanent and releases any database locks currently held by this Connection object. This method should be used only when auto-commit mode has been disabled.
    • You need to commit your code after execute() method or you can set setAutoCommit(true).

     setInt(), setString(), setDate() ...etc

    • In my program I have used setInt() and setString() methods.
    • Each method consist of Parameter index and value.
      • setInt( int ParameterIndex, int value )
    • This method sets the value according to the given parameter and then the driver converts this into SQL Integer value.

    Think about following code that I have used,

    String insertTable = "INSERT INTO student" + "(id,name,age,city)VALUES" + "(? , ? , ? , ?)";
                PSInsert.setInt(1, 8);               //Index is 1, value is 8
                PSInsert.setString(2, "Sean");       //Index is 2, value is 'Sean'
                PSInsert.setInt(3, 26);              //Index is 3, value is 26
                PSInsert.setString(4, "Colombo");    //Index is 4, value is 'Colombo'


    • This is another special method which is used to roll back all the changes that we have created in the database, if there are any error while transaction.
    • This method is used in the catch() block.
    • This method should be used only when auto-commit mode has been disabled( setAutoCommit(false) ).

    Finally I have closed prepared statements and the connection.