8 Replies - 7927 Views - Last Post: 30 July 2008 - 10:13 PM Rate Topic: -----

#1 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1642
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Connect to POP3 server

Posted 30 July 2008 - 07:30 PM

Well someone asked how to do this so I thought Id whip up something to help them along. Im trying to connect to a POP3 server (trying Gmail for the time being) to check my email. The code I have doesn't execute after the line NetworkStream stream = client.GetStream(), where client is a TcpClient object. I get no exceptions so I'm having a hard time tracking the problem down. I've tried it two different ways (Ill show both).

The first is in a Windows Application

private void Pop3Check()
{

    string serverResponse;
    int messageCount;
    string emailFrom = "";
    string emailSubject = "";

    try
    {
        // Create a TCP client for a TCP connection
        client = new TcpClient();
        client.Connect("pop.gmail.com", 995);
    }
    catch (SocketException ex)
    {
        MessageBox.Show(ex.Message);
    }

    // Create a network stream to retrieve data from the TCP client
    NetworkStream stream = client.GetStream(); //<-- stops executing here

    // We need a stream reader to be able to read the network stream
    StreamReader reader = new StreamReader(stream);
    StreamWriter writer = new StreamWriter(stream);

    try
    {
        serverResponse = reader.ReadLine(); //Get opening POP3 banner
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }


    writer.WriteLine("USER " + txtUser.Text); //Send username
    writer.Flush();

    serverResponse = reader.ReadLine();

    if (serverResponse.Substring(0, 4) == "-ERR")
    {
        status += "Unable to log into server";
        return;
    }

    writer.WriteLine("PASS " + txtPass.Text);  //Send password
    writer.Flush();

    try
    {
        serverResponse = reader.ReadLine();
    }
    catch (IOException)
    {
        status += "Unable to log into server";
        return;
    }

    if (serverResponse.Substring(0, 3) == "-ER")
    {
        status += "Unable to log into server";
        return;
    }

    writer.WriteLine("STAT"); //Send stat command to get number of messages
    writer.Flush();

    serverResponse = reader.ReadLine();

    string[] count = serverResponse.Split(' ');

    messageCount = Convert.ToInt32(count[1]);

    if (messageCount > 0)
    {
        status += "You have " + messageCount + " message(s)";
    }
    else
    {
        status += "You have no messages";
    }

    for (int i = 1; i <= messageCount; i++)
    {
        writer.WriteLine("TOP " + i + " 0"); //read header of each message
        writer.Flush();

        serverResponse = reader.ReadLine();

        while (true)
        {
            serverResponse = reader.ReadLine();
            if (serverResponse == ".") break;
            if (serverResponse.Length > 4)
            {
                if (serverResponse.Substring(0, 5) == "From:") emailFrom = serverResponse;
                if (serverResponse.Substring(0, 8) == "Subject:") emailSubject = serverResponse;
            }
        }
        messages.Items.Add(i + "  " + emailFrom + "  " + emailSubject);
    }
}



This code doesn't throw any errors, but it seems to stop executing at the line specified.

My second attempt I tried in a web based application. I get more of a response here, but if you look at the attached screen shot you'll see what my issue is. I do a Response.Write to see what the response is (as I get an error) and the screen shot shows what I see

Attached Image

public string SendCommand(ref NetworkStream stream, string msg)
{
    byte[] data = Encoding.ASCII.GetBytes(msg.ToCharArray());
    stream.Write(data, 0, data.Length);
    //Response.Write(msg);
    return GetResponse(ref stream);
}

// check if there is a response to get and return it
public string GetResponse(ref NetworkStream stream)
{
    byte[] bytes = new byte[client.ReceiveBufferSize + 1];
    int ret = stream.Read(bytes, 0, bytes.Length);
    StreamReader reader = new StreamReader(stream);
    // Returns the data received 
    Response.Write(Encoding.ASCII.GetString(bytes));
    return Encoding.ASCII.GetString(bytes);
}



public void ReadMail(string host, string user, string pass)
{
    // initialise objects	
    NetworkStream stream;
    string hostResponse;

    // open connection to server
    try
    {
        client.Connect(host, 995);
    }
    catch (Exception ex)
    {
        Response.Write(ex.Message);
        Response.End();
    }

    // get response
    stream = client.GetStream();

    hostResponse = GetResponse(ref stream);

    // enter user name
    hostResponse = SendCommand(ref stream, "USER " + user);

    // enter password
    hostResponse = SendCommand(ref stream, "PASS " + pass);

    // check if logged in ok
    if (!(hostResponse.Substring(0,4) == "-ERR"))
    {
        Response.Write("Login Successful!");
    }
    else
    {
        Response.Write("Invalid login. Please try again<BR>");
        Response.Write("<p>" + hostResponse + "</p>");
        Response.End();
    }

    hostResponse = SendCommand(ref stream, "STAT");

    string[] tmpArray;

    tmpArray = hostResponse.Split();

    string numMess = tmpArray[0];

    Response.Write("<p><hr></p>");

    hostResponse = "";

    Response.Write("Number of Messages: " + numMess);
    Response.End();
    if (Convert.ToInt32(numMess) > 0)
    {
        Response.Write("Messages: " + numMess + "<br>");
        for (int i = 1; i <= Convert.ToInt32(numMess); i++)
        {
            hostResponse += SendCommand(ref stream, "TOP " + i + " 10");
        }
    }
    else
    {
        Response.Write("Messages: None" + "<br>");
    }

    hostResponse += SendCommand(ref stream, "STAT");
    
    tmpArray = hostResponse.Split("+OK".ToCharArray());

    for (int j = 1; j <= tmpArray.Length - 1; j++)
    {
        Response.Write("<h3>#" + j + "</h3>" + tmpArray[j] + "<br/>");
    }

    // close connection
    hostResponse = SendCommand(ref stream, "QUIT" );
    client.Close();
}



Anyone got any ideas what I'm doing wrong here?

Is This A Good Question/Topic? 0
  • +

Replies To: Connect to POP3 server

#2 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1642
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Re: Connect to POP3 server

Posted 30 July 2008 - 07:44 PM

I resolved this issue. I replaced the NetworkStream with


SslStream stream = new SslStream(client.GetStream());

stream.AuthenticateAsClient("pop.gmail.com");



And the Windows Application works like a charm now. Thanks for reading :)
Was This Post Helpful? 1
  • +
  • -

#3 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1642
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Re: Connect to POP3 server

Posted 30 July 2008 - 08:27 PM

I got another question. I've searched and haven't found anything too promising yet, so Im hoping someone here has done this before. I can connect to the POP3 server, I can receive the list of emails, I can even view each email individually when selected. The problem I'm having is the way the email looks when displayed. This is what I get

Attached Image

Has anyone done any POP3 work and had to parse all this crap out?
Was This Post Helpful? 0
  • +
  • -

#4 no2pencil  Icon User is offline

  • Admiral Fancy Pants
  • member icon

Reputation: 5388
  • View blog
  • Posts: 27,383
  • Joined: 10-May 07

Re: Connect to POP3 server

Posted 30 July 2008 - 08:36 PM

View PostPsychoCoder, on 30 Jul, 2008 - 11:27 PM, said:

The problem I'm having is the way the email looks when displayed.

Yeah... parts of it are all blurry!
Was This Post Helpful? 0
  • +
  • -

#5 Jayman  Icon User is offline

  • Student of Life
  • member icon

Reputation: 418
  • View blog
  • Posts: 9,532
  • Joined: 26-December 05

Re: Connect to POP3 server

Posted 30 July 2008 - 08:46 PM

ROFL....too funny, no2. Sorry, I am of no use here, I just had to comment on the funny. :)
Was This Post Helpful? 0
  • +
  • -

#6 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1642
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Re: Connect to POP3 server

Posted 30 July 2008 - 09:05 PM

ROFL No2!

I was blurring out the IP's and email addresses. Thanks for making me laugh, I could really use it
Was This Post Helpful? 0
  • +
  • -

#7 no2pencil  Icon User is offline

  • Admiral Fancy Pants
  • member icon

Reputation: 5388
  • View blog
  • Posts: 27,383
  • Joined: 10-May 07

Re: Connect to POP3 server

Posted 30 July 2008 - 09:09 PM

These are standard email headers. In outlook you can see these by right clicking your email & selection message options. It's at the very bottom, labeled internet headers.
Was This Post Helpful? 0
  • +
  • -

#8 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4421
  • View blog
  • Posts: 12,286
  • Joined: 18-April 07

Re: Connect to POP3 server

Posted 30 July 2008 - 09:18 PM

The trick here is the part where it shows "boundary" this is a unique line of characters which break the parts of the email into its body, headers, attachments etc.

So pull this string out (it will begin with "--") and use it in a regular expression split to break the email apart. Once you do this, you will see that each section contains a simple header followed by its content.

The rest is caaaaaake :)

Edit: your example's boundary is the part that reads ---=_NextPart_000_0047_01C8F281.6EBD1E90

This post has been edited by Martyr2: 30 July 2008 - 09:20 PM

Was This Post Helpful? 1

#9 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1642
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Re: Connect to POP3 server

Posted 30 July 2008 - 10:13 PM

Thanks Marty! Now I get to do what I truly love, parsing with Regular Expressions! Ill post the solution I come up with so all can benefit from it, and will also write two tutorials - one for web based, one for windows based.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1