Click here to Skip to main content
Licence CPOL
First Posted 2 Jul 2005
Views 117,769
Downloads 2,525
Bookmarked 38 times

Retrieving Mail with POP3

By Chad Z. Hower aka Kudzu | 2 Jul 2005
In this article I will demonstrate how to quickly and easily retrieve mail messages using the POP3 protocol.
2 votes, 18.2%
1

2
3 votes, 27.3%
3
1 vote, 9.1%
4
5 votes, 45.5%
5
3.04/5 - 11 votes
μ 3.04, σa 2.74 [?]

Introduction

In this article, I will demonstrate how to quickly and easily retrieve mail messages using the POP3 protocol.

Why Console?

The demo code is a console application. For simple code snippets, I prefer console applications as they are easy to write and focus on the code without the demo being over shadowed by the interface code. All of the code demonstrated here can of course be used in Win Forms, Web Forms, Web service or any other type of applications.

What is Indy?

This demo uses classes from the open source library Indy.Sockets. Indy.Sockets is an open source socket library that supports clients, servers, TCP, UDP, raw sockets, as well as over 100 higher level protocols such as SMTP, POP3, NNTP, HTTP and many more. Indy.Sockets is available for C#, C++, Delphi, Visual Basic. NET, or any .NET language, and Kylix.

The code

try {
    // You will need to set these to your settings.
    // The settings here are settings for a local 
    // demo POP3 server
    // that I use for testing.
    string xHost = "127.0.0.1";
    string xUsername = "chad";
    string xPassword = "pass"; 
    using (POP3 xPOP3 = new POP3()) {
        xPOP3.Username = xUsername;
        xPOP3.Password = xPassword;
        xPOP3.Connect(xHost); 
        int xCount = xPOP3.CheckMessages();
        if (xCount == 0) {
            Console.WriteLine("No messages on account.");
        } 
        else {
            Message xMsg = new Message();
            xPOP3.Retrieve(1, xMsg);
            Console.WriteLine("Subject: " + xMsg.Subject);
            Console.WriteLine("From: " + xMsg.From.Text);
            Console.WriteLine("To: " + xMsg.Recipients[0].Text);
            Console.WriteLine();
            Console.WriteLine(xMsg.Body.Text);
        }
        try {
        } 
        finally {
            xPOP3.Disconnect();
        }
    }
} 
catch (Exception e) {
    Console.WriteLine(e.Message);
}
Console.WriteLine("");
Console.WriteLine("Press enter");
Console.ReadLine();

The code is very simple. The POP3 server is connected by using the host, username and the password provided. The CheckMessages method is called to obtain the number of messages in the mailbox. If at least one message exists, the first message is retrieved. Note the use of the Message class this is a special container that parses the mail message and its headers for easy access by the developer. Note the explicit use of the Disconnect method. In TCP protocols it's good to explicitly disconnect and with the POP3 protocol it is especially important as POP3 is transactional. Failing to call Disconnect will cause the POP3 server to rollback any messages deleted during the connection.

Running the demo

It is important to change these lines:

string xHost = "127.0.0.1";
string xUsername = "chad";
string xPassword = "pass";

You need to fill in these with the settings for your POP3 server.

Output

Running the demo will produce an output similar to this, if you have a message in your mailbox:

Subject: Hello
From: chad@test.com
To: chad@local.net

Hello, this is a test message.

Press enter.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Chad Z. Hower aka Kudzu

Other

Cyprus Cyprus

Member
Chad Z. Hower, a.k.a. Kudzu
"Programming is an art form that fights back"
Website: http://www.KudzuWorld.com
Blogspace: http://www.KudzuWorld.com/blogs/
Speaking Profile: http://www.woo-hoo.net/
 
Formerly the Regional Developer Adviser (DPE) for Microsoft MEA (Middle East and Africa), he was responsible for 85 countries spanning 4 continents and crossing 10 time zones. Now Chad is Microsoft MVP and a professional speaker at popular developer conferences worldwide. Chad was once introduced as having "mastered more languages than a United Nations translator." Chad is the author of the book Indy in Depth and has contributed to several other books on network communications and general programming. Chad has lived in Canada, Cyprus, Switzerland, France, Jordan, Russia, Turkey, and the United States. In total Chad has visited more than 50 countries, visiting most of them many times.

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. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralAbout downloading attached file to mail Pinmemberfriendprach20:45 8 Oct '09  
GeneralPlease I need your Help Pinmembervampraider1215:25 6 Feb '09  
I'am try to make a Inbox With Indy But I cant read the mail correctly; all the message appers like this
 
this is my code


 
string body = "";
Indy.Sockets.Text MP = (Indy.Sockets.Text)xMsg.MessageParts[0];
body = MP.Body.GetText();
string CadenaBody = "";
CadenaBody += body + "";
 
Indy.Sockets.AttachmentFile MailAttachement;
foreach (MessagePart mpp in xMsg.MessageParts)
{
if (mpp.GetType().ToString() == "Indy.Sockets.AttachmentFile")
{
MailAttachement = (Indy.Sockets.AttachmentFile)mpp;
if (MailAttachement.FileName != "")
{
MailAttachement.SaveToFile("C:/");
CadenaBody = CadenaBody + "Attached File: " + MailAttachement.FileName.ToString() + "
";
}
 
}
}
CadenaBody = CadenaBody + "
___________________FIN DE MENSAJE____________________" + "
" + "
";
 
Response.Write(CadenaBody);
 

 

------=_NextPart_001_01DB_01C98073.CFEDEAC0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable was checked by NOD32 antivirus system. http://www.eset.com ------=_NextPart_001_01DB_01C98073.CFEDEAC0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Enviamos una cordial que hoy cumple = a=F1os.
 


 

 
=A0=A0=A0=A0
 
=A0
 
__________ NOD32 3831 (20090205) Information __________
 
This message was checked by NOD32 antivirus system.
http://www.eset.com
------=_NextPart_001_01DB_01C98073.CFEDEAC0-- ------=_NextPart_000_01DA_01C98073.CFEDEAC0 Content-Type: image/jpeg; name="image001.jpg" Content-Transfer-Encoding: base64 Content-ID: /9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAoHBwgHBgoICAgLCgoLDhgQDg0NDh0VFhEYIx8lJCIf IiEmKzcvJik0KSEiMEExNDk7Pj4+JS5ESUM8SDc9Pjv/2wBDAQoLCw4NDhwQEBw7KCIoOzs7Ozs7 Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozv/wAARCAF7AjgDASIA AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJico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sv+fSL/vmrNFAFb+zb L/n0i/75o/s2y/59Iv8AvmrNFAFb+zbL/n0i/wC+aP7Nsv8An0i/75qzRQBW/s2y/wCfSL/vmj+z bL/n0i/75qzRQBW/s2y/59Iv++aP7Nsv+fSL/vmrNFAFb+zbL/n0i/75o/s2y/59Iv8AvmrNFAFb +zbL/n0i/wC+aP7Nsv8An0i/75qzRQBW/s2y/wCfSL/vmj+zbL/n0i/75qzRQBW/s2y/59Iv++aP 7Nsv+fSL/vmrNFAFb+zbL/n0i/75o/s2y/59Iv8AvmrNFAFb+zbL/n0i/wC+aP7Nsv8An0i/75qz RQBW/s2y/wCfSL/vmj+zbL/n0i/75qzRQBW/s2y/59Iv++aP7Nsv+fSL/vmrNFAHMNbQbj+6Xqe1 J9mg/wCeS/lUzfeb6mkrtsjnucJ4qmlhik8qWSPE+BtcjjmuW+3Xn/P3cf8Af1v8a6bxf/qpf+vj /GuSrrwiTp/M5cS3
 




QuestionUnable to log on PinmemberMember 31084179:06 13 Dec '08  
AnswerRe: Unable to log on PinmemberChad Z. Hower aka Kudzu14:00 13 Dec '08  
QuestionNO Connection Could Be Made Because the Target Machine Actively Refused It Pinmemberoerslaafroze6:37 27 Nov '07  
GeneralMIME Format PinmemberAlan (Engeman)1:50 21 Sep '07  
QuestionAmbiguous reference Pinmembertheplayer0112:33 23 Aug '07  
AnswerRe: Ambiguous reference PinmemberChad Z. Hower aka Kudzu11:23 26 Aug '07  
QuestionNeed Help Pinmemberkanzz20:48 2 Aug '07  
GeneralSample for actual release of Indy.Sockets Pinmembertim.taylor3:51 16 Jul '07  
GeneralMessage body is blank PinmemberPaolo Ramos7:18 29 Nov '06  
GeneralRe: Message body is blank PinmemberChad Z. Hower aka Kudzu8:52 29 Nov '06  
GeneralRe: Message body is blank PinmemberMember 39053636:45 29 Nov '08  
QuestionMessage Dates Pinmemberecs.dp5:50 29 Aug '06  
AnswerRe: Message Dates Pinmemberghiutzu3:37 25 Aug '08  
GeneralSSL PinmemberAMGG0:13 7 Aug '06  
GeneralRe: SSL PinmemberChad Z. Hower aka Kudzu0:45 8 Aug '06  
GeneralRe: SSL PinmemberNiladri Mahapatra21:43 9 Apr '07  
GeneralFirst Message always empty PinmemberHaggy4:00 6 Jul '06  
GeneralRe: First Message always empty PinmemberChad Z. Hower aka Kudzu8:40 6 Jul '06  
GeneralMIME & VS2005 PinmemberHaggy3:49 6 Jul '06  
QuestionNot working with Yahoo emails Pinmemberboodi_812:24 19 May '06  
QuestionHow to retrieve only unread messages Pinmembernewbie137:56 18 Apr '06  
AnswerRe: How to retrieve only unread messages PinmemberChad Z. Hower aka Kudzu9:24 20 Apr '06  
Questionsave Attachment Pinmemberr78095:41 20 Feb '06  

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120210.1 | Last Updated 2 Jul 2005
Article Copyright 2005 by Chad Z. Hower aka Kudzu
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid