Click here to Skip to main content
Click here to Skip to main content

Retrieve Mail From a POP3 Server Using C#

By , 19 Jan 2002
 

Sample Image - GUI.gif

Introduction

In this article, I'll show you how to retrieve mail from POP server based on RFC 1725.

Algorithm for Retrieving Mail

To retrieve mail from POP server, I just follow rule of RFC 1725. You also can download that paper (RFC 1725). 

Here's the algorithm:   

 Client   : +OK Server POP  Ready!!
 Client   : USER xxx
 Server   : +OK
 Client   : PASS yyy
 Server   : +OK user successfully logged on
 Client   : STAT
 Server   : +OK n m
 Client   : RETR 1
 Server   : +OK
               ---{ data }-----
 Client   : QUIT
 Server   : +OK Server POP signing off

Implementation

It's easy to implement an application if we know the algorithm to retrieve mail from a POP server. In this article, I use the TcpClient and NetworkStream classes. Firstly, declare public variables:

 public TcpClient Server;
 public NetworkStream NetStrm;
 public StreamReader  RdStrm;
 public string Data;
 public byte[] szData;
 public string CRLF = "\r\n";

Here's the code for when the Connect Button is clicked:

private void ConnectBtn_Click(object sender, System.EventArgs e)
{
    // change cursor into wait cursor
    Cursor cr = Cursor.Current;
    Cursor.Current = Cursors.WaitCursor;

    // create server POP3 with port 110
    Server = new TcpClient(POPServ.Text,110);
    Status.Items.Clear();

    try
    {
        // initialization
        NetStrm = Server.GetStream();
        RdStrm= new StreamReader(Server.GetStream());
        Status.Items.Add(RdStrm.ReadLine());

        // Login Process
        Data = "USER "+ User.Text+CRLF;
        szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray());
        NetStrm.Write(szData,0,szData.Length);
        Status.Items.Add(RdStrm.ReadLine());

        Data = "PASS "+ Passw.Text+CRLF;
        szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray());
        NetStrm.Write(szData,0,szData.Length);
        Status.Items.Add(RdStrm.ReadLine());

        // Send STAT command to get information ie: number of mail and size
        Data = "STAT"+CRLF;
        szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray());
        NetStrm.Write(szData,0,szData.Length);
        Status.Items.Add(RdStrm.ReadLine());

        // change enabled - disabled button
        ConnectBtn.Enabled = false;
        DisconnectBtn.Enabled = true;
        RetrieveBtn.Enabled = true;

        // back to normal cursor
        Cursor.Current = cr;

    }
    catch(InvalidOperationException err)
    {
        Status.Items.Add("Error: "+err.ToString());
    }
}    

Here's the code for when the Disconnect Button is clicked:

private void DisconnectBtn_Click(object sender, System.EventArgs e)
{
    // change cursor into wait cursor
    Cursor cr = Cursor.Current;
    Cursor.Current = Cursors.WaitCursor;

    // Send QUIT command to close session from POP server
    Data = "QUIT"+CRLF;
    szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray());
    NetStrm.Write(szData,0,szData.Length);
    Status.Items.Add(RdStrm.ReadLine());

    //close connection
    NetStrm.Close();
    RdStrm.Close();

    // change enabled - disabled button
    ConnectBtn.Enabled = true;
    DisconnectBtn.Enabled = false;
    RetrieveBtn.Enabled = false;

    // back to normal cursor
    Cursor.Current = cr;
}

Here's code when Retrieve Button clicked:

private void RetrieveBtn_Click(object sender, System.EventArgs e)
{
    // change cursor into wait cursor
    Cursor cr = Cursor.Current;
    Cursor.Current = Cursors.WaitCursor;
    string szTemp;
    Message.Clear();
    try
    {
        // retrieve mail with number mail parameter
        Data = "RETR "+ Number.Text+CRLF;
        szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray());
        NetStrm.Write(szData,0,szData.Length);

        szTemp = RdStrm.ReadLine();
        if(szTemp[0]!='-') 
        {
        
            while(szTemp!=".")
            {
                Message.Text += szTemp;
                szTemp = RdStrm.ReadLine();
            }
        }
        else
        {
            Status.Items.Add(szTemp);
        }
        
        // back to normal cursor
        Cursor.Current = cr;

    }
    catch(InvalidOperationException err)
    {
        Status.Items.Add("Error: "+err.ToString());
    }

}

Testing

Build and run this project. Set the POP server, user and password. After that you'll get a response message from the POP server (you can see on status box) ie: +OK 2 624 if success or -ERR if fail. The words "+OK 2 624" mean you have two emails and total size 624.

Now, you can set the mail message number and then click Retrieve button. Then you'll get the mail according to the mail number that you wrote on Mail Number Box.

Reference

  • MSDN for .NET framework
  • RFC 1725

History

20 Jan 2002 - fixed non-critical GUI problem

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Agus Kurniawan
Founder PE College
Indonesia Indonesia
Member
He gradueted from Sepuluh Nopember Institute of Technology (ITS) in Department of Electrical Engineering, Indonesia. His programming interest is VC++, C#, VB, VB.NET, .NET, VBScript, Delphi, C++ Builder, Assembly,and ASP/ASP.NET. He's founder for PE College(www.pecollege.net), free video tutorial about programming, infrastructure, and computer science. He's currently based in Depok, Indonesia. His blog is http://geeks.netindonesia.net/blogs/agus and http://blog.aguskurniawan.net

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionGet the total number of emails in Inboxmemberviragdesai30 Apr '13 - 20:15 
How can i get the total number of emails? Is there a way by which I can get total number of emails in the Inbox?
QuestionI connect but I see no emailsmembermuslera4 Nov '12 - 12:09 
Hello all,
 
I have a problem at using this program, and hopefully you can help me... I connect correctly to pop.gmail.com but the program says that I have 0 mails in my inbox, when actually I have 2... I can see them if I use Outlook but however if I run the program I can not see anyone.
 
Do you know what's happening? I'd thank you very much if you could help me...
 
Thanks a lot. Best regards,
 
Muslera
Questiononly get a part of mailsmembersbmzhcn21 Sep '12 - 22:54 
in my gmail has 3000 mails, but use the prog only get 273 or 263 mails. Also, the mails is a oldest mails. how to get latest mails , and i want to get all mails. not a part
QuestionConnection problems!memberMember 376860924 Jul '12 - 0:11 
Greetings,
 
I'm relatively new to network programming was skimming through the article and tried the code but it didn't work. Then, with some surfing through MSDN documentation and the Internet resources other than MSDN, I found about SslStream and decided to use it instead of NetworkStream class. I replaced the SslStream in place of NetworkStream and Viola! It started working like it never stopped! So anyone trying the code please use SslStream in System.Net.Security namespace instead of NetworkStream. Enjoy!
 
Regards!
Hushhhhhhhhh

QuestionI am getting the errormemberT. Abdul Rahman9 Dec '11 - 19:38 
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 74.125.53.109:110
Generalvalue cannot be null ;parameter name : itemmemberyoga arista8 Feb '11 - 23:24 
help me pliz,,when i try to vb.net,,i got some error like this
 
"argument : value cannot be null
parameter name : item"
 
can somebody help me,,what error this means?
Generalmail foldersmemberstijnn_1713 Dec '10 - 8:57 
is there any way to get the mails that are located in folders instead of the inbox?
 
thanks in advance
GeneralRe: mail foldersmemberkirnyk25 Apr '11 - 4:37 
Dear stijnn_17,
 
Have you got any answer on your question. i'm looking for this answer. please help if you know how to access junk mail folder using pop3 classes
Generalvalue can not be null...memberlsb_safari16 Sep '10 - 8:53 
Hi,
It gives error in this line
 
Status.Items.Add(RdStrm.ReadLine());
 
Error:- Value can't be null
 
Please tell me the solution
Thanks
QuestionHow to Read folder lik "junk" or any customized folder on mailserver?memberjymitra19 Jul '10 - 21:46 
HI ,,
What if i want to access email from customized folder it may b any folder lik person name or junk ?
please help me about this topic .i hv done R&D lot but no result ..please help me ..
 
email me @ jymitra03@gmail.com

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 20 Jan 2002
Article Copyright 2002 by Agus Kurniawan
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid