Click here to Skip to main content
15,868,016 members
Articles / Programming Languages / C#

Receiving Mail through the POP3 Protocol & MIME Parser

Rate me:
Please Sign up or sign in to vote.
4.50/5 (6 votes)
29 Sep 2011CPOL 39.1K   3.1K   25   6
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)


Written By
Web Developer Kbyte.Ru
Russian Federation Russian Federation
Started programming in 1998 on the G-Basic and QBasic.

At various times worked with programming languages and technologies: Visaul Basic, Delphi, C, Visual C++, Java, PHP, ASP VBScript and JScript.

Currently engaged in programming based on .NET Framework technologies. Mainly the development of websites on the ASP.NET MVC, C#, TypeScript, SCSS and also database programming (SQL Server and PostgreSQL).

In 2016 started the AdminStock.net - solutions for administrators.

Comments and Discussions

 
QuestionHow can I show the content of the mail in aspx page itself Pin
bhaskarjoardar7-May-15 21:24
bhaskarjoardar7-May-15 21:24 
AnswerRe: How can I show the content of the mail in aspx page itself Pin
fatman4519-Jun-15 10:14
professionalfatman4519-Jun-15 10:14 
GeneralI Get The Error Pin
knsivam8919-Jul-12 19:51
knsivam8919-Jul-12 19:51 
QuestionmyPop3 is not retrive any message or mail Pin
Rajendra.b17-Jul-12 19:37
Rajendra.b17-Jul-12 19:37 
Questiondoes this work with hotmail? Pin
mowali19752-May-12 12:09
mowali19752-May-12 12:09 
QuestionReadLine and ReadToEnd methods Pin
Ivar Lumi28-Sep-11 22:24
Ivar Lumi28-Sep-11 22:24 

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

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