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

POP3 Email Client (.NET 2.0)

By , 4 Aug 2006
 

Introduction

The .NET framework 2.0 has revamped the support of email sending with improved SMTP classes, but receiving emails is still missing. There are various articles on CodeProject for POP3 support, but all have some drawbacks such as

  • some code is not managed
  • use of DLLs without .NET source code
  • too limited functionality and error reporting
  • no tracing of server commands and responses
  • no support for SSL
  • no XML documentation, etc.

This project builds on the previous projects, but is written entirely in C# 2.0. The present first article focuses on the downloading of raw emails from a POP3 server (RFC1939). There are methods to connect to a POP3 server, to get a list of available emails, to request some emails, to delete some emails and to disconnect. For debugging and for professional use, extensive error reporting and communication tracing is provided. A future article will decompose the received raw email into body, alternative views and attachments following the MIME specification.

I used Gmail for testing, which is freely available for anyone (recommended).

This code is based on the following work:

Background

Interacting with a POP3 Server

Downloading an email from a POP3 server is rather straight forward. The communication with a POP3 server uses only few commands and is easily human readable. Once a connection, possibly with SSL, is established, the client needs to provide a user name and password to enter the POP3 state TRANSACTION, called 'connected' in Pop3MailClient.

In the connected (POP3: transaction) state, the client can execute the following commands:

  • STAT: GetMailboxStats(), number of mails and size of mailbox
  • LIST: GetEmailIdList(), a list with session message numbers and size for all emails
  • LIST [msg]: GetEmailSize(), session message number and size for just one email
  • UIDL: GetUniqueEmailIdList(), a list with unique ID numbers and session message numbers for all emails
  • NOOP: NOOP(), No operation, just check if server is still alive
  • RETR msg: GetRawEmail(), retrieve one complete email
  • DELE msg: DeleteEmail(), Mark one email for deletion once the connection is properly closed
  • RSET: UndeleteAllEmails(), POP3 server deletes unmarks the emails marked for deletion
  • QUIT: Disconnect(), POP3 server deletes emails as needed and closes TCP connection

For a better understanding, it is recommended to read the official POP3 specification, RFC1939 from IETF: Post Office Protocol - Version 3.

Error Handling & Tracing

Quite a number of things can go wrong when two computers communicate over the Internet. Therefore, solid error reporting and communication tracing is essential. Some problems, like no response form the server are fatal and throw an exception. After an exception, usually the connection is dead and needs to be rebuilt. If the error is detected by the POP3 client code, a Pop3Exception (inherited from ApplicationException) is thrown, otherwise it is a normal .NET exception. Some problems, like trying to retrieve a non existing email, raise just a Warning event. It is up to the user of the POP3 client code to decide if an exception should be thrown in the Warning event or a warning written into a log file or ... After a warning, the POP3 server is ready for the next command.

To further help with the investigation of communication problems, a Trace event is raised. It shows commands and responses exchanged between PopClient and PopServer, including warnings. It is strongly recommended to use this feature in the beginning of a project, because RFC1939 gives the server implementor great freedom. It often provides additional information which can be seen in the trace.

Using the code

Server Settings

I feel the server settings like IP address, etc. should not change within a session. The Pop3MailClient requires servername, port, should SSL be used, username and password in the constructor and they cannot be changed. If you want to connect to a different server or for a different user, create a new Pop3MailClient.

To get the demo code running, you need to enter your own credentials for username and password in the following line:

// TODO: Replace username and password with your own credentials.
Pop3.Pop3MailClient DemoClient =
  new Pop3.Pop3MailClient(
    "pop.gmail.com", 995, true, "Username@gmail.com", "password");

If you don't use Gmail, of course you need to also change the servername and port number, maybe even set useSSL to false.

Reading Raw Email

The method GetRawEmail returns the complete email content for one particular message number. RFC1939 specifies that only ANSI characters can be used and therefore the raw email can be easily displayed. But of course it might look funny because of special characters or encoding. Decoding an email will be part of the next article about my Pop3MimeClient class.

AutoReconnect after server timeout

I tested the code extensively with Gmail, which sometimes simply fails to respond. If the isAutoReconnect property is set, the Pop3MailClient tries to reconnect exactly once after a timeout. That's all it usually takes, but notice that any emails marked for deletion are not deleted on the server.

Points of Interest

Efficiency

My guess is that the garbage collector spends a considerable amount of time with collecting memory. Receiving email is a lot of text processing and the idea of all these strings created and discarded gives me a creepy feeling. I hear you saying, use Stringbuilders, but they can be even slower than strings if only few operations are executed with them. Isn't it time for some recycling, i.e. reusing the same global StringBuilder for every email received? I was careful not to introduce any concurrency problems. But even the Framework itself is not reentrant ! If the repeated use of StringBuffers troubles you, just make them local.

Gmail

I had a good experience using Gmail, although I encountered 2 flaws:

  • Gmail shows maximal 250-260 mails in a mailbox, even if there are thousands. Gmail shows the oldest emails. As soon some emails get deleted (after disconnect), newer emails get available.
  • The response of Gmail is sometimes slow and sometimes there is just no response.

History

  • Update 5.August.2006: Fixed some bugs because autoreconnect didn't work properly
  • Update 1.July.2006: The code now supports connections with or without SSL. The UseSSL flag in the Pop3MailClient constructor indicates if the connection is with SSL or without
  • Version 1.0: One POP3 command I didn't need and therefore didn't implement was UIDL [id], which retrieves the message number for an unique ID

License

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

About the Author

Peter Huber SG
Web Developer
Singapore Singapore
Member
SW Dev Manager from Switzerland living in Singapore
 
I would be very interested to do SW development in Singapore for an international .NET project.

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

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionI connect but I see no emailsmemberthiago martins do carmo5 Apr '13 - 8:41 
QuestionWhere I get Email IDsmemberMuhammad Mohiuddin Bukhari26 Feb '13 - 21:06 
Questionretrive email by pop3 in .net2memberMember 969113021 Dec '12 - 19:54 
Questioncannot connect to exchange servermemberMember 910346511 Dec '12 - 23:56 
QuestionI connect but I see no emailsmembermuslera4 Nov '12 - 12:45 
QuestionConverting from plan to mailmemberEduardo Mass12 Oct '12 - 6:27 
BugGetEmailIdList() always returns 0 records [modified]membersuhail wani13 Sep '12 - 8:05 
Questionhow can i create my own mailing system using asp.net 3.5memberKhanFaiz7 Sep '12 - 20:24 
QuestionThanks for the post, how can i get the mail subjects?membermodemode5 Jun '12 - 12:07 
Questionhow to fetch the attachment file in the mailmemberklita131 May '12 - 10:55 
QuestionHow to save attachment to local harddisk?memberWilson Chow8 May '12 - 18:06 
QuestionA connection attempt failedmemberMember 811792327 Apr '12 - 6:30 
Questionhow can reduce ReadTimeout of Pop3MimeClientmemberrpc.ragesh14 Mar '12 - 2:22 
AnswerRe: how can reduce ReadTimeout of Pop3MimeClientmemberrpc.ragesh15 Mar '12 - 2:22 
GeneralMy vote of 5memberMd Kamruzzaman Sarker25 Nov '11 - 20:17 
QuestionNo connection could be made because the target machine actively refused it 74.125.127.109:995memberRamajayam198919 Nov '11 - 2:45 
QuestionPop3MimeClientmemberSumit Kumar Singh India24 Oct '11 - 2:40 
GeneralRead Email Special charsmemberelliot_pineda3 May '11 - 14:45 
GeneralMy vote of 5membersampsonlau4 Apr '11 - 18:33 
Generalproblem with msg uid > returning sizemembereidylon11 Mar '11 - 9:57 
GeneralRe: problem with msg uid > returning sizemembereidylon11 Mar '11 - 10:20 
GeneralMy vote of 5memberAshish Tyagi 4021 Feb '11 - 6:47 
GeneralMy vote of 5memberburleyman248 Feb '11 - 9:28 
GeneralMy vote of 5membermhn21724 Sep '10 - 23:57 
GeneralMy vote of 5memberhamid.khan13524 Sep '10 - 2:35 
GeneralMy vote of 3memberThien La Duc13 Sep '10 - 16:42 
GeneralRe: My vote of 3mvpNishant Sivakumar2 Oct '10 - 10:12 
QuestionGMAIL???memberhesaigo999ca3 Aug '10 - 6:48 
AnswerRe: GMAIL???memberGregoryagu4 Aug '10 - 14:24 
GeneralRe: GMAIL???memberhesaigo999ca6 Aug '10 - 7:38 
GeneralRe: GMAIL???memberhesaigo999ca7 Aug '10 - 9:57 
QuestionHow to Read folder lik "junk" or any customized folder on mailserver? Pinmemberjymitra19 Jul '10 - 21:45 
GeneralI am looking into VB.net version; Do any body have that? Please Would be greate helpmemberr_ozone4 Jun '10 - 3:57 
GeneralRe: I am looking into VB.net version; Do any body have that? Please Would be greate helpmemberWinXpProme8 Jun '10 - 11:46 
GeneralRe: I am looking into VB.net version; Do any body have that? Please Would be greate helpmemberrpc.ragesh15 Mar '12 - 2:23 
GeneralDetermine original sendermembermick12325 May '10 - 6:51 
GeneralReading email seems to be failing [modified]memberCaden17 Dec '09 - 6:55 
QuestionHow to decode the subject?memberMikla7825 Nov '09 - 5:12 
AnswerRe: How to decode the subject?memberPeter Huber SG25 Nov '09 - 13:18 
GeneralMark message as readmemberthomasabcd21 Sep '09 - 9:20 
GeneralRe: Mark message as readmembertokfrans5 Oct '09 - 5:21 
Generalsmall real world(?) patchmembertb200017 Sep '09 - 4:19 
QuestionHow to Track Bounce Back Emailmembergowrikaran198414 Aug '09 - 3:00 
AnswerRe: How to Track Bounce Back EmailmemberPeter Huber SG14 Aug '09 - 15:31 
Generali'm attempting a re-writememberYankee Imperialist Dog!13 Jul '09 - 9:43 
GeneralAttachments.memberIgor11111116 May '09 - 21:48 
GeneralRe: Attachments.membertb200017 Sep '09 - 4:22 
Questionhow to get count of unread email?memberchjlcn11 Oct '08 - 18:40 
Generalgmail usage, is there a waymemberhesaigo999ca8 Oct '08 - 9:19 
GeneralSuparb Ummmmmmh u are genius... and true Social WorkermemberMember 449891225 Sep '08 - 19:21 

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 5 Aug 2006
Article Copyright 2006 by Peter Huber SG
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid