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.
Pop3Lib.Client myPop3 = new Pop3Lib.Client
("pop.gmail.com", "username@gmail.com", "password", 995);
Pop3Lib.MailItem m;
while (myPop3.NextMail(out m))
{
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"))
{
myPop3.Delete();
Console.WriteLine("Mail is marked for remove.");
}
}
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);
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()));
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));
}
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)
{
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
{
if (this.Headers.ContainsKey("Message-Id"))
{
return this.Headers["Message-Id"].ToString();
}
return String.Empty;
}
}
}
}
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