- 论坛徽章:
- 0
|
简单的C#代码就可以实现pop3邮箱的监控
namespace Sky.MailMonitor
{
public class Pop3
{
private const int bufsize = 1024; //default 1kbytes buffers
//服务器确认消息的状态码,必须是大写的
private const string OKFlag = "+OK";
private const string ERRFlag = "-ERR";
private int _port = 110;
public int Port
{
get
{
return _port;
}
set
{
_port = value;
}
}
private int mailCount = 0;
public int MailCount
{
get
{
return mailCount;
}
set
{
mailCount = value;
}
}
private int mailSpace = 0;
public int MailSpace
{
get
{
return mailSpace;
}
set
{
mailSpace = value;
}
}
private Socket socket = null;
public int port
{
get
{ return Port; }
}
//step 1: 连接一个POP3服务器,希望得到+OK的确认消息
public void Connect(string hostname)
{
//建立一个套接字
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPHostEntry hostInfo = Dns.GetHostByName(hostname);
IPEndPoint endPoint = new IPEndPoint(hostInfo.AddressList[0], Port);
socket.Connect(endPoint);
string tmp = RecvLine(); //blocking,wait for '+OK'
Console.WriteLine(tmp);
}
//step 2:发送命令字USER和PASS
public void Login(string username,string password)
{
SendCommand("USER " + username);
string tmp=RecvLine();
Console.WriteLine("Server say: {0}", tmp);
SendCommand("PASS " + password);
string tmp1=RecvLine();
Console.WriteLine("Server say: {0}", tmp1);
}
//step 3:发送命令字STAT,请求服务器发回关于邮箱的统计资料,如邮件总数和总字节数
//C:STAT
//S:+OK nn mm
//nn是邮件数量,mm是大小
public void Stat()
{
SendCommand("STAT");
string tmp=RecvLine();
tmp = tmp.Substring(tmp.IndexOf(" ") + 1); //在+OK和一个空格之后得到邮件数量,字节数
string tmp1 = tmp.Substring(0, tmp.IndexOf(" ")).Trim();
MailCount=Int32.Parse(tmp.Substring(0, tmp.IndexOf(" ")).Trim());
Console.WriteLine("Server say: {0}", tmp);
// MailSpace = Int32.Parse(tmp1.Substring(0, tmp1.IndexOf(" ")).Trim());
}
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/31179/showart_266411.html |
|