MailReaderCMD

MailReaderCMD is a simple program to read email from an IMAP mailbox using the javax.mail classes. It shows how to connect to a mail box, navigate to the appropriate folder, download messages and print out their contents. To keep things simple it doesn't show the contents of MIMe messages.

To run this program you will need to download the javax.mail and javax.activation packages and make sure they are in your class path. (In OS X this means putting them in the /Library/Java/extensions).

Connecting to an IMAP mailbox and getting a message basically consists of the following steps

As you can see there are many steps involved. This is to preserve flexibility. If you are writing an application that needs to access mailboxes, you should be able to encapsulate all the functionality into a more specialized object.

//
//  MailReaderCMD.java
//  MailReaderCMD
//
//  Created by Mark W. Shead on 8/8/04.

import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.event.*;
import javax.mail.internet.*;
import javax.activation.*;


/* Simple command line utility to read messages from
* an IMAP mailbox.
*/
public class MailReaderCMD 
{
  Store store = null;
  Message[] messages = null;
  URLName urlName = null;
  Properties properties = null;
  Session mailSession = null;
  int numberOfMessages = 10;
  
  /* Should be called as:
    * java MailReaderCMD imap://username:password@mailhost <number of messages>
    */
  public static void main (String args[]) {
        System.out.println("Starting MailReaderCMD");
    MailReaderCMD mrc = new MailReaderCMD();
    mrc.initialize(args);
    mrc.getMessages();
  }
  
  public void initialize(String [] args) {
    if(args.length < 2) {
      System.out.println("only received " + args.length 
                 " arguments");
      System.out.println("usage: java MailReaderCMD " +
                         "imap://username:password@mailhost " +
                         "<number of messages>");
      System.exit(0);
    }
    urlName = new URLName(args[0]);
    numberOfMessages =  Integer.parseInt(args[1]);
    
    messages = new Message[numberOfMessages];
    System.out.println("Getting system properties...");
    Properties props = System.getProperties();
    System.out.println("Getting instance of javax.mail.Session...");
    mailSession = Session.getInstance(props);
    try {
      System.out.println("Connecting to the mail store...");
      store = mailSession.getStore(urlName);
      store.connect();
    }
    catch (Exception e) {
      System.out.println("Error connecting .... \n");
      System.out.println(e);
      System.exit(1);
    }
    return;
  }
  
  public void getMessages() {
    try {
      System.out.println("Getting default folder from the store...");
      Folder folder = store.getDefaultFolder();
      System.out.println("Getting INBOX from default folder...");
      folder = folder.getFolder("INBOX");
      System.out.println("Opening INBOX as read only...");
      folder.open(folder.READ_ONLY);
      System.out.println("Counting the number of messages in INBOX...");
      int totalMessages = folder.getMessageCount();
      System.out.println("INBOX contains " + totalMessages);
      for(int i = numberOfMessages - 1; i > -1; i--) {
        System.out.println("Getting Message #" (totalMessages - i));
        String message = 
          messageString(folder.getMessage(totalMessages - i));
        System.out.println(message);
      }
    }
    catch(Exception e) {
      System.out.println(e);
    }
    
    return;
  }
  
  /* Takes retrieve a message and returns a string with
    * the content of the message.  Doesn't show mime encoded
    * messages.
    */
  public String messageString(Message message) {
    String str = "";
    try {
      //The from field is an array.  I'm not sure why because it seems
      //that there could only be one from address.
      Address [] from = message.getFrom();
      for(int i = 0; i < from.length; i++)
        str = str +"from: " + from[i"\n";
      
      Address [] to = message.getAllRecipients();
      for(int i = 0; i<to.length; i ++)
        str = str + "to: " + to[i"\n";
      
      str = str + "Received On: " + message.getReceivedDate() "\n";
      str = str + "\n" + message.getContent() "\n";
    }
    catch (Exception e) {
      System.out.println("There was an error reading the message");
      System.out.println(e);
    }
    return str;
  }
}