自制Pop3邮件接收系统(一):利用MatchEvaluator实现HZ的解码 

要作自制的Pop3邮件接收系统,就要自己处理邮件的编码

大家可能会收到以下的“乱码”,
~{4s<R:C#,NRJG~}qiushuiwuhen~{#,;6S-@45=~}csdn.

实际上是简体中文的HZ编码,在邮件中经常会出现,

因为邮件协议体系通常是七位的,而汉字却是双字节的

所以就使用以下的方法对其进行解码

String hzDecode(Match m){
 String tmp=m.ToString();
 byte[] ret=new byte[tmp.Length-4];
 for(int i=0;i<ret.Length;i++)
  ret[i]=(byte)(tmp[i+2]+128);
 return Encoding.GetEncoding(936).GetString(ret);
}


使用范例:
  string strHz="~{4s<R:C#,NRJG~}qiushuiwuhen~{#,;6S-@45=~}csdn.";
  strHz=Regex.Replace(strHz,@"~\{(.+?)~\}",new MatchEvaluator(hzDecode));
  Response.Write("\nHZ Decode="+strHz);


随便带上编码的代码(可用来发送邮件用)

String hzEncode(Match m){
 byte[] tmp=Encoding.GetEncoding(936).GetBytes(m.ToString());
 StringBuilder ret=new StringBuilder("~{");
 for(int i=0;i<tmp.Length;i++)
  ret.Append((char)(tmp[i]-128));
 ret.Append("~}");
 return ret.ToString(); 
}

使用范例:
  string strHz="大家好,我是qiushuiwuhen,欢迎来到csdn.";
  strHz=Regex.Replace(strHz,@"[^\x00-\xff]+",new MatchEvaluator(hzEncode));
  Response.Write("<xmp>HZ Encode="+strHz);

原理:使用MatchEvaluator的回调(CallBack)函数执行Regex的替换操作

自制Pop3邮件接收系统(二):利用TcpClient得到Pop3的邮件列表数据   

Pop3接收数据,参见
http://www.aspalliance.com/chrisg/default.asp?article=93

改成c#代码,并修改了一些bug

1.用的是ASCII,并不适合国内的邮件读取
解决方法:改为Encoding.GetEncoding(936)
2.GetResponse并不是堵塞方式,没有完全下载数据
解决方法:设置一个strEnd标志,来判断是否结束
3.GetResponse每次都要返回ReceiveBufferSize长的数据
解决方法:根据接收到数据长度,返回缓冲中的对应长度的数据
等等..

System.Net.Sockets.TcpClient tcpC;
System.Net.Sockets.NetworkStream netStream;
string SendCommand(string sToSend){
 byte[] bData=Encoding.GetEncoding(936).GetBytes(sToSend+Environment.NewLine);
 netStream.Write(bData,0,bData.Length);
 return GetResponse();
}

string GetResponse(){
  byte[] bData=new byte[tcpC.ReceiveBufferSize];
  int iRec=netStream.Read(bData, 0, bData.Length);
  return Encoding.GetEncoding(936).GetString(bData,0,iRec);
}
string ReadMail(string ps,string un,string pw){
 tcpC=new System.Net.Sockets.TcpClient(ps,110);
 netStream = tcpC.GetStream();
 string strResponse=GetResponse();
 string strNL=Environment.NewLine;
 string strEnd=strNL+"."+strNL+"+OK "+strNL;
 SendCommand("user "+un);
 SendCommand("pass "+pw);
 strResponse=SendCommand("stat");
 int iCount=Int32.Parse(strResponse.Split(' ')[1]);
 Response.Write(iCount + " Messages");
 for(int i=1;i<iCount;i++)strResponse+=SendCommand("top "+i+" 0");
 strResponse+=SendCommand("QUIT");
 while(!strResponse.EndsWith(strEnd))strResponse+=GetResponse();
 tcpC.Close();
 return strResponse;
}

调用方法:
 ReadMail(pop3Server,username,password)

ps.简化了代码,取消了一些异常的捕捉,是为了让大家看得清楚明白.