Jump to content

How to connect to POP3 server using Java socket?

- - - - -

  • Please log in to reply
3 replies to this topic

#1
thatsme

thatsme

    Programmer

  • Members
  • PipPipPipPip
  • 176 posts
Hi. I am quite new to java socket programming. I have to implement protocol of pop3 server. I found the code below which should do that. However, i cannot find out what parameters I should pass to connect and login methods to connect to pop3 server (parameters typed in are copied from example). Is there any POP3 server class in java or should i implement server myself? Any help would be appreciated

class Main{
    public static void main(String[] args) throws IOException {
        POP3Client client = new POP3Client();
        //client.setDebug(true);
        client.connect("pop3.myserver.com");
        client.login("name@myserver.com", "password");
        System.out.println("Number of new emails: " + client.getNumberOfNewMessages());
        LinkedList<Message> messages = client.getMessages();
        for (int index = 0; index < messages.size(); index++) {
        System.out.println("--- Message num. " + index + " ---");
        System.out.println(messages.get(index).getBody());
        }
        client.logout();
        client.disconnect();
    }
}

public class POP3Client {
    private Socket clientSocket;
    private boolean debug = false;
    private BufferedReader in;
    private BufferedWriter out;
    private static final int PORT = 110;
    
    public boolean isDebug() {
        return debug;
    }
    
    public void connect(String host, int port) throws IOException {
        debug = true;
        clientSocket = new Socket();
        clientSocket.connect(new InetSocketAddress(host, port));
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        out = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
        if (debug)
            System.out.println("Connected to the host");
        readResponseLine();
    }
    
    public void connect(String host) throws IOException {
        connect(host, PORT);
    }
    
    public boolean isConnected() {
        return clientSocket != null && clientSocket.isConnected();
    }
    
    public void disconnect() throws IOException {
        if (!isConnected())
            throw new IllegalStateException("Not connected to a host");
        clientSocket.close();
        in = null;
        out = null;
        if (debug)
            System.out.println("Disconnected from the host");
    }
    
    protected String readResponseLine() throws IOException{
        String response = in.readLine();
        if (debug) {
            System.out.println("DEBUG [in] : " + response);
        }
        if (response.startsWith("-ERR"))
            throw new RuntimeException("Server has returned an error: " + response.replaceFirst("-ERR ", ""));
        return response;
    }
    
    protected String sendCommand(String command) throws IOException {
        if (debug) {
        System.out.println("DEBUG [out]: " + command);
        }
        out.write(command + "\n");
        out.flush();
        return readResponseLine();
    }
    
    public void login(String username, String password) throws IOException {
        sendCommand("USER " + username);
        sendCommand("PASS " + password);
    }

    public void logout() throws IOException {
        sendCommand("QUIT");
    }
    
    public int getNumberOfNewMessages() throws IOException {
        String response = sendCommand("STAT");
        String[] values = response.split(" ");
        return Integer.parseInt(values[1]); //value[0] - busena, value[1] - pranesimu skaicius value[2] - pranesimu uzimama vieta
    }
    
    protected Message getMessage(int messageNumber) throws IOException {
        String response = sendCommand("RETR " + messageNumber);
        HashMap<String, LinkedList<String>> headers = new HashMap<String, LinkedList<String>>();
        String headerName = null;
        // process headers
        while ((response = readResponseLine()).length() != 0) {
            if (response.startsWith("\t")) 
            continue; //no process of multiline headers
        
            int colonPosition = response.indexOf(":");
            headerName = response.substring(0, colonPosition);
            String headerValue;
            if (headerName.length() > colonPosition) 
                headerValue = response.substring(colonPosition + 2);
            else
                headerValue = "";
        
            LinkedList<String> headerValues = headers.get(headerName);
            if (headerValues == null){
                headerValues = new LinkedList<String>();
                headers.put(headerName, headerValues);
            }
            headerValues.add(headerValue);
        }
        // process body
        StringBuilder bodyBuilder = new StringBuilder();
        while (!(response = readResponseLine()).equals(".")) {
            bodyBuilder.append(response + "\n");
        }
        return new Message(headers, bodyBuilder.toString());
    }
    
    public LinkedList<Message> getMessages() throws IOException {
        int numOfMessages = getNumberOfNewMessages();
        LinkedList<Message> messageList = new LinkedList<Message>();
        for (int i = 1; i <= numOfMessages; i++) {
            messageList.add(getMessage(i));
        }
        return messageList;
    }
}    


#2
lethalwire

lethalwire

    while(false){ ... }

  • Members
  • PipPipPipPipPipPipPip
  • 748 posts
  • Programming Language:Java, PHP
  • Learning:Java, PHP
Well do you have an email address you could try it on?
I'm not sure if this will work or not, but for example if you have a Hotmail account you could try:


client.connect("pop3.live.com");

        client.login("yourEmailAddress@hotmail.com", "yourPassword");


This might help with other emails:
Incoming and Outgoing Mail Server Settings for Hotmail, Yahoo, Google GMail, AOL, MSN and more

They need specific ports, and ssl enabled.

So you could try something like:

client.connect("pop3.live.com", 995);

client.login("yourEmailAddress@hotmail.com", "yourPassword");



#3
thatsme

thatsme

    Programmer

  • Members
  • PipPipPipPip
  • 176 posts
I have created hotmail account and tried to connect to it the way you told me but i got the exception below. Any more ideas what should i do? Exception in thread "main" java.net.SocketException: Network is unreachable: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at POP3Client.connect(POP3Client.java:26)
at POP3Client.connect(POP3Client.java:35)
at Main.main(Main.java:8)

#4
thatsme

thatsme

    Programmer

  • Members
  • PipPipPipPip
  • 176 posts
I have maneged to connect to google by using ssl. Now in POP3Client's method connect I use these lines to create socket:
SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
        clientSocket = (SSLSocket) sslsocketfactory.createSocket(host, PORT);
However i get the following exeption when i try to authenticate myself by sending username to server in login method
Exception in thread "main" java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at sun.security.ssl.InputRecord.readFully(Unknown Source)
    at sun.security.ssl.InputRecord.read(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.readDataRecord(Unknown Source)
    at sun.security.ssl.AppInputStream.read(Unknown Source)
    at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
    at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
    at sun.nio.cs.StreamDecoder.read(Unknown Source)
    at java.io.InputStreamReader.read(Unknown Source)
    at java.io.BufferedReader.fill(Unknown Source)
    at java.io.BufferedReader.readLine(Unknown Source)
    at java.io.BufferedReader.readLine(Unknown Source)
    at POP3Client.readResponseLine(POP3Client.java:56)
    at POP3Client.sendCommand(POP3Client.java:71)
    at POP3Client.login(POP3Client.java:75)
    at Main.main(Main.java:8)





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users