Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Receiving Mail through the POP3 Protocol & MIME Parser

4.50/5 (6 votes)
29 Sep 2011CPOL 40K   3.1K  
This article describes how to create a simple class library to get the mail through the POP3 protocol and MIME parser.
Article.gif

Introduction

This article describes how to create a simple class library to get the mail through the POP3 protocol and MIME parser.

Using the Code

Class library is ready to use and can be used to receive mail via POP3 on C# and Visual Basic .NET.

C#
//create pop3 client
Pop3Lib.Client myPop3 = new Pop3Lib.Client
			("pop.gmail.com", "username@gmail.com", "password", 995);

// create object for mail item
Pop3Lib.MailItem m;

// read all mails
while (myPop3.NextMail(out m))
{
  // output to console message author and subject
  Console.Write("New message from {0}: {1}", m.From, m.Subject);
  Console.WriteLine("Are you want remove this message (y/n)?");
  if (Console.ReadLine().ToLower().StartsWith("y"))
  {
    // mark current message for remove
    myPop3.Delete();
    Console.WriteLine("Mail is marked for remove.");
  }
}

// close connection
// all the marked messages will be removed
myPop3.Close();

Working with the mail server is via sockets in the Client class. To send commands to the server, use the method Command.

C#
public void Command(string cmd)
{
  if (_Socket == null) 
  {
    throw new Exception("No server connection. Please use the Connect method.");
  }
  WriteToLog("Command: {0}", cmd);// log
  byte[] b = System.Text.Encoding.ASCII.GetBytes(String.Format("{0}\r\n", cmd));
  if (_Socket.Send(b, b.Length, SocketFlags.None) != b.Length)
  {
    throw new Exception("Sorry, error...");
  }
}

To obtain the server response, use two functions. ReadLine function returns only the first line. This function is necessary because for all the data, it can take more time. The second function ReadToEnd returns all data.

C#
public string ReadLine()
{
  byte[] b = new byte[_Socket.ReceiveBufferSize];
  StringBuilder result = new StringBuilder(_Socket.ReceiveBufferSize);
  int s = 0;
  while (_Socket.Poll(1000000, SelectMode.SelectRead) && 
	(s = _Socket.Receive(b, _Socket.ReceiveBufferSize, SocketFlags.None)) > 0)
  {
    result.Append(System.Text.Encoding.ASCII.GetChars(b, 0, s));
  }

  WriteToLog(result.ToString().TrimEnd("\r\n".ToCharArray()));// log

  return result.ToString().TrimEnd("\r\n".ToCharArray());
}

public string ReadToEnd()
{
  byte[] b = new byte[_Socket.ReceiveBufferSize];
  StringBuilder result = new StringBuilder(_Socket.ReceiveBufferSize);
  int s = 0;
  while (_Socket.Poll(1000000, SelectMode.SelectRead) && 
	((s = _Socket.Receive(b, _Socket.ReceiveBufferSize, SocketFlags.None)) > 0))
  {
    result.Append(System.Text.Encoding.ASCII.GetChars(b, 0, s));
  }

  // log
  if (result.Length > 0 && result.ToString().IndexOf("\r\n") != -1)
  {
    WriteToLog(result.ToString().Substring(0, result.ToString().IndexOf("\r\n")));
  }
  // --

  return result.ToString();
}

The Result class is a helper and makes it easy to check response from the server.

C#
Result _ServerResponse = new Result();
_ServerResponse = ReadLine();
if (_ServerResponse.IsError)
{ // server error
  throw new Exception(_ServerResponse.ServerMessage);
}

MailItem class is a helper for email message. You can append to the MailItem class of the new properties for easy access to headers.

C#
namespace Pop3Lib
{
  public class MailItem : MailItemBase
  {
    // ...

    public string MessageId 
    { 
      get
      {
        // check header by name
        if (this.Headers.ContainsKey("Message-Id")) 
        { // the header is found, return value
          return this.Headers["Message-Id"].ToString();
        }
        // the header not found, return empty string
        return String.Empty;
      }
    }
    
    // you can create properties for other headers here
     
    // ...
  }
}

The MailItemBase class parses MIME and content of the message.

History

  • 28th September, 2011: Initial version
  • 29th September, 2011: Fixed small bugs in code blocks

License

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