Click here to Skip to main content
12,624,109 members (29,700 online)
Click here to Skip to main content
Add your own
alternative version

Stats

21.6K views
2.8K downloads
24 bookmarked
Posted

Receiving Mail through the POP3 Protocol & MIME Parser

, 29 Sep 2011 CPOL
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)

Share

About the Author

Alеksey Nemiro
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.

You may also be interested in...

Comments and Discussions

 
QuestionHow can I show the content of the mail in aspx page itself Pin
bhaskarjoardar7-May-15 22:24
memberbhaskarjoardar7-May-15 22:24 
AnswerRe: How can I show the content of the mail in aspx page itself Pin
fatman4519-Jun-15 11:14
professionalfatman4519-Jun-15 11:14 
GeneralI Get The Error Pin
knsivam8919-Jul-12 20:51
memberknsivam8919-Jul-12 20:51 
QuestionmyPop3 is not retrive any message or mail Pin
Rajendra.b17-Jul-12 20:37
memberRajendra.b17-Jul-12 20:37 
Questiondoes this work with hotmail? Pin
mowali19752-May-12 13:09
membermowali19752-May-12 13:09 
QuestionReadLine and ReadToEnd methods Pin
Ivar Lumi28-Sep-11 23:24
memberIvar Lumi28-Sep-11 23: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.

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