Reading message using Java Mail

This Example shows you how to read message using javamail api.

Reading message using Java Mail

Reading message using Java Mail

     

This Example shows you how to read message using javamail api. All messages are stored in Folder objects. A folder can contain folders or messages or both. The Folder class declares methods that fetch, append, copy and delete messages. These are some of the methods used in the program.

System.getProperties() this method get the  system properties.
Session.getDefaultInstance(properties) this method get the default Session object.
session.getStore("pop3") this method get a Store object that implements the pop3 protocol.
store.connect(host, user, password) Connect to the current host using the specified username and password.
store.getFolder("inbox") create a Folder object of the inbox.
folder.open(Folder.READ_ONLY) open the Folder.
folder.getMessages() get all messages for the folder.

ReadMail.java

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

public class ReadMail { 

  public static void main(String args[]) throws Exception { 

  String host = "192.168.10.205";
 
String user = "test";
 
String password = "test"; 

  // Get system properties
  
Properties properties = System.getProperties(); 

  // Get the default Session object.
 
Session session = Session.getDefaultInstance(properties);

  // Get a Store object that implements the specified protocol.
 
Store store = session.getStore("pop3");

  //Connect to the current host using the specified username and password.
 
store.connect(host, user, password);

  //Create a Folder object corresponding to the given name.
 
Folder folder = store.getFolder("inbox");

  // Open the Folder.
 
folder.open(Folder.READ_ONLY);

  Message[] message = folder.getMessages();

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

  System.out.println("------------ Message " + (i + 1) + " ------------");

  System.out.println("SentDate : " + message[i].getSentDate());
 
System.out.println("From : " + message[i].getFrom()[0]);
 
System.out.println("Subject : " + message[i].getSubject());
  System.out.print("Message : ");

  InputStream stream = message[i].getInputStream();
 
while (stream.available() != 0) {
 
System.out.print((char) stream.read());
 
}
 
System.out.println();
 
}

  folder.close(true);
 
store.close();
 
}
}


Output:

------------ Message 1 ------------
SentDate : Tue Jul 15 18:44:41 IST 2008
From : test@localhost
Subject : hi..!
Message : Hi ...... 

------------ Message 2 ------------
SentDate : Tue Jul 15 17:57:32 IST 2008From :
 test <test@localhost>
Subject : Resistance is futile.
Message : Resistance is futile. You will be assimilated!

------------ Message 3 ------------
SentDate : Mon Jul 14 21:10:35 IST 2008
From : test@localhost
Subject : hi..!
Message : Hi this is komal choudhary......

Download code