How can I read a mail message from my mail server?

John Zukowski

The Message objects include writeTo() method. All you have to do is specify a stream to write to. The following program demonstrates this:

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

public class GetMessageExample {
  public static void main (String args[]) throws Exception {
    String host = args[0];
    String username = args[1];
    String password = args[2];

    // Create empty properties
    Properties props = new Properties();

    // Get session
    Session session = Session.getInstance(props, null);

    // Get the store
    Store store = session.getStore("pop3");
    store.connect(host, username, password);

    // Get folder
    Folder folder = store.getFolder("INBOX");;

    BufferedReader reader = new BufferedReader (
      new InputStreamReader(;

    // Get directory
    Message message[] = folder.getMessages();
    for (int i=0, n=message.length; i<n; i++) {
       System.out.println(i + ": " + message[i].getFrom()[0] 
         + "	" + message[i].getSubject());

        "Do you want to read message? [YES to read/QUIT to end]");
      String line = reader.readLine();
      // Mark as deleted if appropriate
      if ("YES".equals(line)) {
      } else if ("QUIT".equals(line)) {

    // Close connection 

For really long messages, you might want to display the output in a TextArea instead of to System.out.

0 Comments  (click to add your comment)
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact