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.io.*;
import java.util.*;
import javax.mail.*;

public class ReadMail {
    public ReadMail() {
        
        try{
            Scanner scn = new Scanner(System.in);
            
            //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("pop3.live.com", userName, password);
            }
            else if("@gmail".equalsIgnoreCase(host)){
                mailStore.connect("pop.gmail.com", userName, password);
            }
            else if("@yahoo".equalsIgnoreCase(host)){
                mailStore.connect("pop.mail.yahoo.com", userName, password);
            }
            else{
                System.out.println("We cannot access to your mail provider");
            }

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

            //Section 6
            for (int i = 1, j=msg.length; i < j ; i++) {
                System.out.println("\n--------------------------------------------------");
                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());
                System.out.println("----------------------------------------------------");
         
                //Section 7
                System.out.println("\nDo you want to continue reading ? [Yes or No]");
                String userIn = mailReader.readLine();

                if("yes".equalsIgnoreCase(userIn)){
                    System.out.println(msg[i].getContent());
                }
                else if("no".equalsIgnoreCase(userIn)){
                    System.exit(0);
                }
                else{
                    System.out.println("wrong entry");
                    System.exit(0);
                }
            }
            
            //Section 8
            mailFolder.close(false);
            mailStore.close();
            
            //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){
                System.out.println(e.toString());
            }
    }
    
    //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. http://easyjavase.blogspot.com/2013/11/string-class-02-special-methods-of.html#.U1sPIvmSxip

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...



Simple Java application to read mails Simple Java application to read mails Reviewed by Ravi Yasas on 10:18 PM Rating: 5

No comments:

Powered by Blogger.