⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 pop3connection.cs

📁 POP3接收邮件源码
💻 CS
字号:
using System;
using System.ComponentModel;
using System.Net.Sockets;
using System.IO;
using System.Text;

namespace Pop3Com
{
	/// <summary>
	/// Pop3 的摘要说明:Pop3类完成邮件的接收功能。
	/// </summary>
	public class Pop3: Component
	{
		private string _host = "127.0.0.1";
		private int _port = 110;
		private string _userName;
		private string _passWord;
		private int _numOfMails;
		private double _totalSize;
		private string _body;
		private string _status;
		private Pop3Connection con;
		private const string CRLF = "\r\n";
		private const string serverConfig = "服务器配置";
		private const string reciveEvent = "接收事件";

		public delegate void MailRecivedDelegate();
		[Category(reciveEvent)]    [Description("邮件接收成功触发的事件")]
		public event MailRecivedDelegate OnMailRecived;
		[Category(serverConfig)]
		public string Host
		{
			get{return _host;}
			set
			{
				if (value == null || value.Trim().Length == 0)
				{
					throw new ArgumentException("无效的主机名");
				}
				_host = value;
			}
		}
		[Category(serverConfig)]
		public int Port
		{
			get{return _port;}
			set
			{
				if (value <= 0)
				{
					throw new ArgumentException("无效的端口");
				}
				_port = value;
			}
		}
		[Category(serverConfig)]
		public string UserName
		{
			get{return _userName;}
			set
			{
				if (value == null || value.Trim().Length == 0)
				{
					throw new ArgumentException("无效的用户名");
				}
				_userName = value;
			}
		}
		[Category(serverConfig)]
		public string PassWord
		{
			get{return _passWord;}
			set
			{
				if (value == null || value.Trim().Length == 0)
				{
					throw new ArgumentException("无效的密码");
				}
				_passWord = value;
			}
		}
		[Browsable(false)]
		public int NumOfMails
		{
			get{return _numOfMails;}
		}
		[Browsable(false)]
		public double TotalSize
		{
			get{return _totalSize;}
		}
		[Browsable(false)]
		public string Body
		{
			get{return _body;}
		}
		[Browsable(false)]
		public string Status
		{
			get{return _status;}
		}

		/// <summary>
		/// 接收邮件信息
		/// </summary>
		public void ReciveMessage()
		{
			//避免线程冲突
			lock(this)
			{
				// 设置初始连接
				con = new Pop3Connection();
				if (_port <= 0)
					_port = 110;
				con.Open(_host, _port);
				
				StringBuilder buf = new StringBuilder();
				string response;
				int code;
				
				// 获取欢迎信息
				con.GetReply(out response,out code);
				_status += response;

				//登录服务器过程
				buf.Append("USER");
				buf.Append(_userName);
				buf.Append(CRLF);
				con.SendCommand(buf.ToString());
				con.GetReply(out response, out code);
				_status += response;
				
				buf.Length = 0;
				buf.Append("PASS");
				buf.Append(_passWord);
				buf.Append(CRLF);
				con.SendCommand(buf.ToString());
				con.GetReply(out response, out code);
				_status += response;

				//向服务器发送STAT命令,从而取得邮箱的相关信息:邮件数量和大小
				buf.Length = 0;
				buf.Append("STAT");
				buf.Append(CRLF);
				con.SendCommand(buf.ToString());
				con.GetReply(out response, out code);
				_status += response;

				//将总邮件数和邮件大小分离
				string[] totalStat = response.Split(new char[]{' '});
				_numOfMails = Int32.Parse(totalStat[1]);
				_totalSize = (double)Int32.Parse(totalStat[2]);
				
				for(int i = 0; i < _numOfMails; i++)
				{
					//根据邮件编号从服务器获得相应邮件
					buf.Length = 0;
					buf.Append("RETR");
					buf.Append(i.ToString());
					buf.Append(CRLF);
					con.SendCommand(buf.ToString());
					con.GetReply(out response, out code);

					if (response[0] != '-')
					{
						//不断地读取邮件内容,只到结束标志:英文句号
						while(response != ".")
						{
							_body += response;
							con.GetReply(out response, out code);
						}
					}
					else
						_status += response;
				}

				//向服务器发送QUIT命令从而结束和POP3服务器的会话
				buf.Length = 0;
				buf.Append("QUIT");
				buf.Append(CRLF);
				con.SendCommand(buf.ToString());
				con.GetReply(out response, out code);
				_status += response;

				con.Close();
				
				// 邮件接收成功后触发的事件
				if (OnMailRecived != null)
				{
					OnMailRecived();
				}
			}
		}
	}

	/// <summary>
	/// Pop3Connection 的摘要说明:Pop3Connection类完成了与主机的连接、通讯和关闭连接等功能。
	/// </summary>
	public class Pop3Connection
	{
		private TcpClient socket;
		private StreamReader reader;
		private StreamWriter writer;
		private bool _connected;

		public bool Connected
		{
			get{return _connected;}
		}

		public Pop3Connection()
		{
			//
			// TODO: 在此处添加构造函数逻辑
			//			
			socket = new TcpClient();
		}


		public void Open(string host, int port)
		{
			if (host == null || host.Trim().Length == 0 || port <= 0)
			{
				throw new ArgumentException("参数值无效");
			}
			try
			{
				socket.Connect(host, port);
				reader = new StreamReader(socket.GetStream(),System.Text.Encoding.ASCII);
				writer = new StreamWriter(socket.GetStream(),System.Text.Encoding.ASCII);
				_connected = true;
			}
			catch(ArgumentNullException)
			{
				throw new ArgumentException("主机名为空,无效的主机名");
			}
			catch(ArgumentOutOfRangeException)
			{
				throw new ArgumentException("端口号port不在主机的最大端口号和最小端口号之间");
			}
			catch(ObjectDisposedException)
			{
				throw new ArgumentException("主机TcpClient 被关闭");
			}
		}
		internal void SendCommand(string cmd)
		{
			try
			{
				writer.WriteLine(cmd);
				writer.Flush();
			}
			catch(Exception e)
			{
				throw new ArgumentException(e.Message);
			}
		}
		internal void GetReply(out string reply, out int code)
		{
			try
			{
				reply = reader.ReadLine();
			}
			catch(Exception e)
			{
				throw new ArgumentException(e.Message);
			}
			code = -1;//reply == null ? -1 : Int32.Parse(reply.Substring(0, 3)); 
		}
		internal void Close()
		{
			reader.Close();
			writer.Flush();
			writer.Close();
			reader = null;
			writer = null;
			socket.Close();
			_connected = false;
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -