Reading POP3 email with Java

You can try the optional package JavaMail (check out this category).

If you know the POP commands, you can write a pop client yourself. Here’s an example:

POPEmail.java:

import java.io.*;
import java.net.*;
 
public class POPEmail
{
    private Socket popSocket;
    private String popHost;
    private String username;
    private String password;
    private BufferedReader br;
    private BufferedWriter bw;
       
    private String smtpHost;
    
    public POPEmail(String popHost, String username, String password) throws IOException {
        this.popHost = popHost;
        this.username = username;
        this.password = password;
    }
    
    public void connect() throws IOException {
        popSocket = new Socket(popHost, 110);
        br = new BufferedReader(new InputStreamReader(popSocket.getInputStream()));        
        bw = new BufferedWriter(new OutputStreamWriter(popSocket.getOutputStream()));
        send("USER " + username);
        receive();
        send("PASS " + password);
        String status = receive();
        if (status.startsWith("-ERR"))
            throw new java.io.IOException("ERROR: USER/PASSW WRONG.");
    }
    
    public void disconnect() throws IOException {
        send("QUIT");
        receive();
        popSocket.close();
    }
    
    private void send(String str) throws IOException {
        //System.out.println("Sending: " + str);
        bw.write(str + "rn");
        bw.flush();
    }
    
    private String receive() throws IOException {
        String str = br.readLine();
        //System.out.println("Receiving: " + str);
        return str;
    }
    
    public int getMessageCount() {
        try {
            send("LIST");
            int n = 0;
            String line = receive();
            while (!line.equals(".")) {
                line = receive();
                try {
                    if (!line.equals("."))
                        n = Integer.parseInt(line.substring(0, line.indexOf(" ")));
                }
                catch(NumberFormatException nfe) { }
            }
            
            return n;
        }
        catch(IOException e) { }
        
        return 0;
    }
    
    public EmailMessage getMessage(int messagenumber) throws IOException {
        send("RETR " + messagenumber);
        String status = receive();
        if (status.startsWith("-ERR")) throw new IOException("Message does not exist!");
        else {
            StringBuffer stringMsg = new StringBuffer();
            String line;
            do {
                line = receive();
                stringMsg.append(line + "rn");
            } while (!line.equals("."));
            
            EmailMessage message = new EmailMessage();
            message.parse(stringMsg.toString());
            return message;
        }
    }
}

EmailMessage.java:

import java.util.*;
 
public class EmailMessage implements java.io.Serializable
{
    public String from;
    public String replyTo;
    public String to;
    public String subject;
    public String date;
    public String MIMEVersion;
    public String priority;
    public String contentType;
    public String body;
    
    public EmailMessage() {
        from = replyTo = to = subject = date = 
              MIMEVersion = priority = contentType = body = "";
    }
    
    public void parse(String message) {
        StringTokenizer st = new StringTokenizer(message, "rn");
        while (st.hasMoreElements()) {
            String line = (String) st.nextElement();
            //System.out.println("parsing: " + line);
            
            if (line.startsWith("From:"))
                from = line.substring(6);
            else if (line.startsWith("Reply-To:"))
                replyTo = line.substring(10);
            else if (line.startsWith("To:"))
                to = line.substring(4);
            else if (line.startsWith("Subject:"))
                subject = line.substring(9);
            else if (line.startsWith("Date:"))
                date = line.substring(6);
            else if (line.startsWith("MIME-Version:"))
                MIMEVersion = line.substring(14);
            else if (line.startsWith("X-Priority:"))
                priority = line.substring(12);
            else if (line.startsWith("Content-Type:"))
                contentType = line.substring(14);
            else if (line.trim().equals("")) {  // body
                StringBuffer sb = new StringBuffer();
                while (!line.equals(".")) {
                    sb.append(line);
                    line = (String) st.nextElement();
                }
            }    
        }
    }
    
    public String toString() {
        return "From: " + from + "rn" +
               "To: " + to + "rn" + 
               "Reply-To: " + replyTo + "rn" +
               "Subject: " + subject + "rn";
    }
}

Main.java:

import java.io.*; 
 
public class Main {
   public static void main(String[] args) {
      if (args.length != 3) {
         System.err.println("usage: java Main <POP server> <user> <pass>");
         System.exit(1);
      }
  
      try {
         POPEmail pop = new POPEmail(args[0], args[1], args[2]);
         pop.connect();
         System.out.println("There are " + pop.getMessageCount() + " message(s) waiting...");
         pop.disconnect();
      }
      catch(IOException e) {
         e.printStackTrace();
      }           
   }
}