自制Pop3郵件接收系統(二):利用TcpClient得到Pop3的郵件列表資料 (轉)

amyz發表於2007-10-17
自制Pop3郵件接收系統(二):利用TcpClient得到Pop3的郵件列表資料 (轉)[@more@]

Pop3接收資料,參見
alliance.com/chrisg/default.asp?article=93">

改成程式碼,並修改了一些

1.用的是ASCII,並不適合國內的讀取
解決方法:改為Encoding.GetEncoding(936)
2.GetResponse並不是堵塞方式,沒有完全資料
解決方法:設定一個strEnd標誌,來判斷是否結束
3.GetResponse每次都要返回ReceiveBufferSize長的資料
解決方法:根據接收到資料長度,返回緩衝中的對應長度的資料
等等..

System.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 Read(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 strResponse+=SendCommand("QUIT");
 while(!strResponse.EndsWith(strEnd))strResponse+=GetResponse();
 tcpC.Close();
 return strResponse;
}

方法:
 ReadMail(pop3Server,username,pass)

ps.簡化了程式碼,取消了一些異常的捕捉,是為了讓大家看得清楚明白.


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10752019/viewspace-977249/,如需轉載,請註明出處,否則將追究法律責任。

相關文章