POP3Demo.java Source code

Java tutorial

Introduction

Here is the source code for POP3Demo.java

Source

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class POP3Demo {
    public static void main(String[] args) throws Exception {
        int POP3Port = 110;
        Socket client = new Socket("127.0.0.1", POP3Port);
        InputStream is = client.getInputStream();
        BufferedReader sockin = new BufferedReader(new InputStreamReader(is));
        OutputStream os = client.getOutputStream();
        PrintWriter sockout = new PrintWriter(os, true);
        String cmd = "user Smith";
        sockout.println(cmd);
        String reply = sockin.readLine();
        cmd = "pass ";
        sockout.println(cmd + "popPassword");
        reply = sockin.readLine();
        cmd = "stat";
        sockout.println(cmd);
        reply = sockin.readLine();
        if (reply == null)
            return;
        cmd = "retr 1";
        sockout.println(cmd);
        if (cmd.toLowerCase().startsWith("retr") && reply.charAt(0) == '+')
            do {
                reply = sockin.readLine();
                System.out.println("S:" + reply);
                if (reply != null && reply.length() > 0)
                    if (reply.charAt(0) == '.')
                        break;
            } while (true);
        cmd = "quit";
        sockout.println(cmd);
        client.close();
    }
}