65.9K
CodeProject 正在变化。 阅读更多。
Home

通过 POP3 协议和 MIME 解析器接收邮件

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.50/5 (6投票s)

2011 年 9 月 28 日

CPOL
viewsIcon

40289

downloadIcon

3142

本文档描述了如何创建一个简单的类库,通过 POP3 协议和 MIME 解析器接收邮件。

Article.gif

引言

本文档描述了如何创建一个简单的类库,通过 POP3 协议和 MIME 解析器接收邮件。

Using the Code

该类库已准备就绪,可用于在 C# 和 Visual Basic .NET 中通过 POP3 接收邮件。

//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();

通过套接字在 Client 类中与邮件服务器进行通信。 使用 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...");
  }
}

要获取服务器响应,请使用两个函数。 ReadLine 函数仅返回第一行。 由于所有数据可能需要更长时间,因此需要此函数。 第二个函数 ReadToEnd 返回所有数据。

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();
}

Result 类是一个辅助类,可以轻松检查服务器的响应。

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

MailItem 类是电子邮件消息的辅助类。 您可以向 MailItem 类添加新的属性,以便轻松访问标头。

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

MailItemBase 类解析 MIME 和消息内容。

历史

  • 2011 年 9 月 28 日:初始版本
  • 2011 年 9 月 29 日:修复代码块中的小错误
© . All rights reserved.