在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#网络编程 → pop3lib类库 +实例(这个不错) 附完整源码下载

pop3lib类库 +实例(这个不错) 附完整源码下载

C#网络编程

下载此实例
  • 开发语言:C#
  • 实例大小:0.07M
  • 下载次数:11
  • 浏览次数:363
  • 发布时间:2013-07-28
  • 实例类别:C#网络编程
  • 发 布 人:crazycode
  • 文件格式:.zip
  • 所需积分:2
 相关标签: POP3 实例

实例介绍

【实例简介】通常情况下,该实例已经够用了                             

【实例截图】

先看demo, demo中 如果选择删除邮件,则真的会删掉服务器的邮件哦

再看结果方案:           

【核心代码】


/*
 * This is example for article: 
 * http://kbyte.ru/ru/Programming/Articles.aspx?id=65&mode=art
 * (only russian language)
 * Author: Aleksey S Nemiro
 * http://aleksey.nemiro.ru
 * http://kbyte.ru
 * August 27, 2011
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Collections;

namespace Pop3Lib
{
  public class Client
  {
    
    private Socket _Socket = null;
    private string _Host = String.Empty;
    private int _Port = 110;
    private string _UserName = String.Empty;
    private string _Password = String.Empty;

    private Result _ServerResponse = new Result();
    private int _Index = 0;

    public int MessageCount = 0;
    public int MessagesSize = 0;
    
    public Client(string host, string userName, string password) : this(host, 110, userName, password) { }
    public Client(string host, int port, string userName, string password)
    {
      // validation
      if (String.IsNullOrEmpty(host)) throw new Exception("Pop3-server is required.");
      if (String.IsNullOrEmpty(userName)) throw new Exception("User name is required.");
      if (String.IsNullOrEmpty(password)) throw new Exception("Password is required.");
      if (port <= 0) port = 110;
      // --

      this._Host = host;
      this._Password = password;
      this._Port = port;
      this._UserName = userName;


      this.Connect();
    }

    /// <summary>
    /// The method connects to the mail server
    /// </summary>
    public void Connect()
    {
      // get server IP
      IPHostEntry myIPHostEntry = Dns.GetHostEntry(_Host);

      if (myIPHostEntry == null || myIPHostEntry.AddressList == null || myIPHostEntry.AddressList.Length <= 0)
      {
        throw new Exception("IP adress not found.");
      }

      // get end pint by IP
      IPEndPoint myIPEndPoint = new IPEndPoint(myIPHostEntry.AddressList[0], _Port);

      // create socket
      _Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      _Socket.ReceiveBufferSize = 512; // 512 byte

      // connect
      WriteToLog("Connecting to server {0}:{1}", _Host, _Port);
      _Socket.Connect(myIPEndPoint);
      // receive a response
      ReadLine();

      // authorization
      Command(String.Format("USER {0}", _UserName));
      ReadLine();

      Command(String.Format("PASS {0}", _Password));
      _ServerResponse = ReadLine();
      // check on the errors
      if (_ServerResponse.IsError)
      {
        throw new Exception(_ServerResponse.ServerMessage);
      }

      // get stat
      Command("STAT");
      _ServerResponse = ReadLine();
      if (_ServerResponse.IsError)
      {
        throw new Exception(_ServerResponse.ServerMessage);
      }

      _ServerResponse.ParseStat(out this.MessageCount, out this.MessagesSize);
    }

    /// <summary>
    /// The method closed the connection to the mail server
    /// </summary>
    public void Close()
    {
      if (_Socket == null) { return; }
      Command("QUIT");
      ReadLine();
      _Socket.Close();
    }

    /// <summary>
    /// The function returns the headers of the said letter
    /// </summary>
    /// <param name="index">Letter index, start with 1</param>
    public Dictionary<string ,object> GetMailHeaders(int index)
    {
      if (index > this.MessageCount)
      {
        throw new Exception(String.Format("The index must be between 1 and {0}", this.MessageCount));
      }
      Command(String.Format("TOP {0} 0", index));
      _ServerResponse = ReadToEnd();
      if (_ServerResponse.IsError)
      {
        throw new Exception(_ServerResponse.ServerMessage);
      }
      MailItem m;
      _ServerResponse.ParseMail(out m);
      return m.Headers;
    }

    /// <summary>
    /// Next letter
    /// </summary>
    public bool NextMail(out MailItem m)
    {
      m = null;
      _Index  ;
      if (_Index > this.MessageCount) return false;// no more letters
      Command(String.Format("RETR {0}", _Index));
      _ServerResponse = ReadToEnd();
      if (_ServerResponse.IsError)
      {
        throw new Exception(_ServerResponse.ServerMessage);
      }
      _ServerResponse.ParseMail(out m);
      return true;
    }

    /// <summary>
    /// Mark current letter for remove
    /// </summary>
    public void Delete()
    {
      Delete(_Index);
    }

    /// <summary>
    /// Mark letter for remove
    /// </summary>
    public void Delete(int index)
    {
      if (index > this.MessageCount)
      {
        throw new Exception(String.Format("The index must be between 1 and {0}", this.MessageCount));
      }
      Command(String.Format("DELE {0}", index));
      _ServerResponse = ReadLine();
      if (_ServerResponse.IsError)
      {
        throw new Exception(_ServerResponse.ServerMessage);
      }
    }

    /// <summary>
    /// The method sends a command to the mail server
    /// </summary>
    /// <param name="cmd">Команда</param>
    public void Command(string cmd)
    {
      if (_Socket == null) throw new Exception("No server connection. Please use the Connect method.");
      WriteToLog("Команда: {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...");
      }
    }

    /// <summary>
    /// Read first line on the server response
    /// </summary>
    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());
    }

    /// <summary>
    /// Read all server response
    /// </summary>
    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();
    }

    // log
    private void WriteToLog(string msg, params object[] args)
    {
      Console.WriteLine("{0}: {1}", DateTime.Now, String.Format(msg, args));
    }
  }
}


标签: POP3 实例

实例下载地址

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警