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

Receiving Mail through the POP3 Protocol & MIME Parser

, 29 Sep 2011
Rate this:
Please Sign up or sign in to vote.
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.

//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.

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.

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.

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.

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)

About the Author

Alеksey Nemiro
Web Developer Kbyte.Ru
Russian Federation Russian Federation
Web Developer. Writer. Author of the Kbyte.Ru.
I like ASP .NET WebForms/MVC, C#, Visual Basic .NET, T-SQL, JavaScript, HTML, CSS, PHP.
Follow on   Twitter

Comments and Discussions

 
GeneralI Get The Error Pinmemberknsivam8919-Jul-12 19:51 
QuestionmyPop3 is not retrive any message or mail PinmemberRajendra.b17-Jul-12 19:37 
Questiondoes this work with hotmail? Pinmembermowali19752-May-12 12:09 
QuestionReadLine and ReadToEnd methods PinmemberIvar Lumi28-Sep-11 22:24 

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140721.1 | Last Updated 29 Sep 2011
Article Copyright 2011 by Alеksey Nemiro
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid