Connecting to a POP3 server using C#

This tutorial will teach you how to create a C# application that connects to a POP3 server and retrieves the email messages. First there is an introduction to connecting to a POP3 server by using Telnet, then the C# sample application follows.

POP3 (Post Office Protocol v3) is a standard protocol for receiving email messages from a POP3 server. Similar to an FTP server, the required credentials for a POP3 server is a username, a password and obviously the address of the server and port (normally this is port 110).

The POP3 server listens for connections on port 110, and when a client tries to connect, he asks for a username and password. If the user is authenthicated successfully, he then can ask send different commands to the server. When the client is satisfied with the server’s response, he sends a “QUIT” message to the POP3 server, and the client disconnects from the server.

Before proceeding, you may want to keep your POP3 account details
closely, so you can test your code. Moreover, as you might already know, you can connect to a POP3 server through Telnet, so to familiarize yourself with the POP3 commands, you can open a Telnet session and connect to your POP3 email server, just like our application will do. This is explained below. If you’re pretty familiar with POP3, you can skip this part and go to the Connect to a POP3 server using C# section below.

Telnet to a POP3 server

You can easily telnet to your POP3 mailbox from anywhere. Before proceeding, I want to let you know that once you start typing a command to Telnet, you shouldn’t use the backspace character. If you do, your command will return an error, because the backspace will be treated as a normal character, and sent so. This is normally not a problem for POP3 servers, since the clients are applications like the one we’re going to build in this tutorial, and the applications don’t make mistakes that can be repaired using backspace. So if you write the command wrong and you need to use backspace, don’t. Instead press enter to send the command, and after the server will return the error, type it all over again.

You start telneting by opening an MSDOS command prompt
and typing telnet:

telnet

Then type OPEN followed by the server name, followed by the port (normally 110). For example, in my case I typed:

OPEN mail.geekpedia.com 110

We need to authenticate, so the next command we’re going to send is the string USER followed by the username:

USER [email protected]

The server asks for the password, which we send:

PASS passgoeshere

Then you can start passing commands, such as LIST to get the full list of messages:

LIST

The list of messages contains the message ID and the message size. If you want to retrieve the content of a message, use the RETR command followed by the message ID:

RETR 1

When you’re done, send the QUIT command to disconnected from the POP3 server:

QUIT

Here’s how my MS-DOS Telnet window looks like after I connected to my email server:

Connect to a POP3 server using C#

First, let’s start by designing a simple form such as the one below, with only the necessary fields where we need to enter the address of the POP3 server (txtServer), port (txtPort), username (txtUser) and password (txtPass). The button in and its Click event, where everything will take place, and a large, multiline textbox where we will be able to follow the connection between the client and the POP3 server.

First we need to add the following using directives so we don’t have to write really long lines of code:

using System.Net.Sockets;

using System.Net.IO;

Now double-click the Connect button (btnConnect) to get to the click event (btnConnect_Click):

private void btnConnect_Click(object sender, EventArgs e)

{


}

As I mentioned earlier, we’re going to write all the code inside the click event of this button, since this is just a sample
on how to connect to a POP3 server. In your release code you’ll probably want to do something more organized, such as writing a method, or even a class.

We start by creating a TCP connection using the TCPClient. We will connect to the server specified in the textboxes (server address and port):

// Create a TCP client for a TCP connection

TcpClient tcpClient = new TcpClient();

// Connect this TCP client to the server IP/name and port specified in the form

tcpClient.Connect(txtServer.Text, Convert.ToInt32(txtPort.Text));

At this point, either the connection will be successful, or the server will not be found and an exception will be returned: SocketException was unhandled: No such host is known. We don’t handle this exception in this code, or any other exception as a matter of fact, since we want to keep the code simple. In production code you will probably want to catch these exceptions and handle them.

Next we’re going to create a NetworkStream object, which we will use to read and write data from and to the server. This NetworkStream instance will be connected to the TCPClient object, which in turn gets the information from the server.

Every time we need to get the messages from the POP3 server, the NetworkStream will return the message as a byte stream, and since we want to transform this stream into readable text we use a StreamReader:

// Create a network stream to retrieve data from the TCP client

NetworkStream netStream = tcpClient.GetStream();

// We need a stream reader to be able to read the network stream

System.IO.StreamReader strReader = new System.IO.StreamReader(netStream);

Now we do a check to see if the connection is successful, since there’s no reason to move forward if it isn’t.

Hopefully it is, so we show the response from the server:

if (tcpClient.Connected)

{

   // Read the server response line from the stream reader

   MessageBox.Show(strReader.ReadLine());

If everything went fine with the connection, you’ll get a response starting with “+OK” . This is, by the way, a good method to check wether or not the server responses are positive: check the first 3 characters of the response, and if they equal “+OK”, everything is going fine.

Before moving on with passing comments to the server, we initialize two objects: WriteBuffer is a byte array which will be holding the commands that we want to pass to the server. enc is the encoding in which we want to pass the commands; and since we’re passing typical text commands, we’re going to use ASCII:

// Buffer to which we're going to write the commands

   byte[] WriteBuffer = new byte[1024];

   // We'll be passing ASCII characters

   ASCIIEncoding enc = new System.Text.ASCIIEncoding();

Only now we start passing commands to the server. I should mention that when you pass commands to a POP3 server, each command must be separated by a new line, which in C# is created using “\r\n” (carriage return and new line).

First we pass the “USER” command. This command is simple: you pass a string such as “USER arthur_vandelay”, where arthur_vandelay is the POP3 user. It is useful to know that in many POP3 servers the user
is the email address itself, but in some servers configurations the user is the part before the “@”, or even a completely different string.

// Pass the username to the server

   WriteBuffer = enc.GetBytes("USER " + txtUser.Text + "\r\n");


   netStream.Write(WriteBuffer, 0, WriteBuffer.Length);

   // Read the server response line from the stream reader

   MessageBox.Show(strReader.ReadLine());

You can see above how we passed the username prefixed by the USER command, and followed by the new line. Then we wrote the bytes to the stream writer, which sends them to the server.

It’s important that we check what the server has to say about our little command, using the ReadLine() method. Supposing everything went fine, you’ll get a message such as “+OK Need a password“. So we’ll send the password to the server, just like we sent the username, but with the PASS command:

// Pass the password to the server

   WriteBuffer = enc.GetBytes("PASS " + txtPass.Text + "\r\n");


   netStream.Write(WriteBuffer, 0, WriteBuffer.Length);

   // Read the server response line from the stream reader

   MessageBox.Show(strReader.ReadLine());

The next message you’re going to receive from the server will contain the total number of messages and their total size. We can follow with other commands now, but one that I’m pretty sure you’ll want to send is LIST which retrieves a list of messages.

The difference between the LIST command and the ones we used before is that it may return multiple lines if there are multiple messages, so we need to use a loop:

// Now that we are (probably) authenticated, list the messages

   WriteBuffer = enc.GetBytes("LIST\r\n");


   netStream.Write(WriteBuffer, 0, WriteBuffer.Length);

   string ListMessage;

   while (true)

   {

      ListMessage = strReader.ReadLine();

      if (ListMessage == ".")

      {

         // It's the last message so exit the loop and continue

         break;

      }

      else

      {

         // List the message

         MessageBox.Show(ListMessage);

         continue;

      }

   }

After we pass the LIST command, we loop through the lines returned by server and display them. With one exception: if the message returned is a dot “.” case in which we exit the loop using break and don’t display anything. Why is that? Simply because when the list of messages is at its end, the POP3 server will return this character to let us know.

If you have any unread messages in your inbox, the first returned line will let you know the number of emails and their total size, similar to the message that you got when you connected to the server. Then will follow each message. Here you might expect to see the subject of the email, the to or from field, or something similar, but you won’t. Instead you will get some numbers, such as “1 5893”. The first number represents the ID of the email message, which will help you in retrieving and deleting messages from the server, and generally keeping track of all the emails. The second number is the size of the email message, in bytes.

To retrieve the content of an email message you can use the “RETR” command and next to it the ID of the message you want to retrieve, such as RETR 1.

We’re getting close to ending this tutorial, but there’s one more thing we need to do: disconnect from the POP3 server using the QUIT command:

WriteBuffer = enc.GetBytes("QUIT\r\n");

   netStream.Write(WriteBuffer, 0, WriteBuffer.Length);

   // Read the server response line from the stream reader

   MessageBox.Show(strReader.ReadLine());

}

The POP3 server will tell you +OK Bye! and that’s it.

Here’s how our C# POP3 checker application looks like in action:

Nathan Pakovskie is an esteemed senior developer and educator in the tech community, best known for his contributions to Geekpedia.com. With a passion for coding and a knack for simplifying complex tech concepts, Nathan has authored several popular tutorials on C# programming, ranging from basic operations to advanced coding techniques. His articles, often characterized by clarity and precision, serve as invaluable resources for both novice and experienced programmers. Beyond his technical expertise, Nathan is an advocate for continuous learning and enjoys exploring emerging technologies in AI and software development. When he’s not coding or writing, Nathan engages in mentoring upcoming developers, emphasizing the importance of both technical skills and creative problem-solving in the ever-evolving world of technology. Specialties: C# Programming, Technical Writing, Software Development, AI Technologies, Educational Outreach

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top