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:
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 '
In the connected (POP3: transaction) state, the client can execute the following commands:
GetMailboxStats(), number of mails and size of mailbox
GetEmailIdList(), a list with session message numbers and size for all emails
- LIST [msg]:
GetEmailSize(), session message number and size for just one email
GetUniqueEmailIdList(), a list with unique ID numbers and session message numbers for all emails
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
UndeleteAllEmails(), POP3 server deletes unmarks the emails marked for deletion
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
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
I feel the server settings like IP address, etc. should not change within a session. The
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
To get the demo code running, you need to enter your own credentials for username and password in the following line:
Pop3.Pop3MailClient DemoClient =
"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
Reading Raw Email
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
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
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.
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.
- 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