发 帖  
原厂入驻New

如何使用C#访问POP3服务器

2008-12-31 16:48:17  12001
分享
<font face="Verdana">如何使用C#访问POP3服务器</font><br/>
<p><font face="Verdana">如何使用C#访问POP3服务器<br/>内容: <br/>This is a follow up to my SMTP example that shows how to <br/>access your POP3 server. This program connects and logs on <br/>to your POP3 server, and checks to see how many new <br/>messages you have. </font></p>
<p><font face="Verdana">The instantiation of the POP is in Main() like this: <br/>POP pop = new POP("pop-server", "loginname", "password"); <br/>You must replace "pop-server" with the name of your POP <br/>server, "loginname" with your own log in, and "password" <br/>with your password. The class has two methods. The Connect <br/>method takes care of actually logging in to the server. The <br/>TCPClient class is used to establish the connection. <br/>The "user" and "pass" commands are used to login. Connect <br/>returns a NetworkStream object created during the <br/>connection process. The second method is <br/>GetNumberOfNewMessages, which returns the number of unread <br/>messages on the server. The response to the "stat" command <br/>is parsed to extract the number of new messages. </font></p><font face="Verdana">
<p><br/>Requirement:</p>
<p>Requires .NET SDK </p>
<p><br/>How To Compile?</p>
<p><br/>csc /r:System.Net.dll /r:System.IO.dll pop.cs&nbsp; </p>
<p>Source Code </p>
<p>using System.Net.Sockets; <br/>using System.IO; <br/>using System.Net; <br/>using System;</p>
<p>class POP <br/>{ <br/>string POPServer; <br/>string user; <br/>string pwd; <br/>public POP(){} <br/>public POP(string server, string _user, string _pwd) <br/>{ <br/>POPServer = server; <br/>user = _user; <br/>pwd = _pwd; <br/>} <br/>private NetworkStream Connect() <br/>{ <br/>TCPClient sender = new TCPClient(POPServer,110); <br/>Byte[] outbytes; <br/>string input; <br/>NetworkStream ns = null; <br/>try{ <br/>ns = sender.GetStream(); <br/>StreamReader sr = new StreamReader(ns); <br/>Console.WriteLine(sr.ReadLine() );</p>
<p>input = "user " + user + "\r\n"; <br/>outbytes = System.Text.Encoding.ASCII.GetBytes<br/>(input.ToCharArray()); <br/>ns.Write(outbytes,0,outbytes.Length) ; <br/>Console.WriteLine(sr.ReadLine() );</p>
<p>input = "pass " + pwd + "\r\n"; <br/>outbytes = System.Text.Encoding.ASCII.GetBytes<br/>(input.ToCharArray()); <br/>ns.Write(outbytes,0,outbytes.Length) ; <br/>Console.WriteLine(sr.ReadLine() );</p>
<p>return ns; <br/>} <br/>catch(InvalidOperationException ioe){ <br/>Console.WriteLine("Could not connect to mail server"); <br/>return ns; <br/>} <br/>} <br/>public int GetNumberOfNewMessages() <br/>{ <br/>Byte[] outbytes; <br/>string input; <br/>try{ <br/>NetworkStream ns = Connect(); <br/>StreamReader sr = new StreamReader(ns);</p>
<p>input = "stat" + "\r\n"; <br/>outbytes = System.Text.Encoding.ASCII.GetBytes<br/>(input.ToCharArray()); <br/>ns.Write(outbytes,0,outbytes.Length); <br/>string resp = sr.ReadLine(); <br/>Console.WriteLine(resp); <br/>string[] tokens = resp.Split(new Char[] {' '});</p>
<p>input = "quit" + "\r\n"; <br/>outbytes = System.Text.Encoding.ASCII.GetBytes<br/>(input.ToCharArray()); <br/>ns.Write(outbytes,0,outbytes.Length); <br/>Console.WriteLine(sr.ReadLine());</p>
<p>sr.Close(); <br/>ns.Close(); <br/>return tokens[1].ToInt32(); <br/>} <br/>catch(InvalidOperationException ioe){ <br/>Console.WriteLine("Could not connect to mail server"); <br/>return 0; <br/>} <br/>} <br/>public static void Main() <br/>{ <br/>POP pop = new POP("pop-server", "loginname", "password"); <br/>Console.WriteLine("New Messages = {0}", <br/>pop.GetNumberOfNewMessages() ); <br/>Console.ReadLine(); <br/>} <br/>}&nbsp;&nbsp; </p>
<p><br/>======================<br/>命令解析部分</p>
<p>private bool SwitchCommand(string POP3_commandTxt)<br/>&nbsp;&nbsp;{<br/>&nbsp;&nbsp;&nbsp;try<br/>&nbsp;&nbsp;&nbsp;{<br/>&nbsp;&nbsp;&nbsp;&nbsp;//---- Parse command --------------------------------------------------//<br/>&nbsp;&nbsp;&nbsp;&nbsp;string[] cmdParts = POP3_commandTxt.Trimstart().Split(new char[]{' '});<br/>&nbsp;&nbsp;&nbsp;&nbsp;string POP3_command = cmdParts[0];<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; POP3_command = POP3_command.ToUpper();<br/>&nbsp;&nbsp;&nbsp;&nbsp;//---------------------------------------------------------------------//</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;//----- loging stuff --------------------------------------------------------------------------//<br/>&nbsp;&nbsp;&nbsp;&nbsp;IF(m_pPOP3_Server.LogCommands){<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;string lCmdTxt = POP3_commandTxt.Replace("\r\n","&lt;CRLF&gt;");<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;m_pLogWriter.AddEntry(lCmdTxt,this.SessionID,m_ConnectedIp,"C");<br/>&nbsp;&nbsp;&nbsp;&nbsp;}<br/>&nbsp;&nbsp;&nbsp;&nbsp;//---- End of loging ---------------------------------------------------------------------------//</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;switch(POP3_command)<br/>&nbsp;&nbsp;&nbsp;&nbsp;{<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case "USER":<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;USER(Core.GetArgsText(POP3_commandTxt,"USER"));<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break;</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case "PASS":<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;PASS(Core.GetArgsText(POP3_commandTxt,"PASS"));<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break;<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case "STAT":<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;STAT();<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break;</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case "LIST":<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;LIST(Core.GetArgsText(POP3_commandTxt,"LIST"));<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break;</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case "RETR":&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;RETR(Core.GetArgsText(POP3_commandTxt,"RETR"));<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break;</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case "DELE":<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;DELE(Core.GetArgsText(POP3_commandTxt,"DELE"));<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break;</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case "NOOP":<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;NOOP();<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break;</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case "RSET":<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;RSET();<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break;</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case "QUIT":<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;QUIT();<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return true;</p>
<p><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//----- Optional commands ----- //<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case "UIDL":<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;UIDL(Core.GetArgsText(POP3_commandTxt,"UIDL"));<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break;</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case "APOP":<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;APOP(Core.GetArgsText(POP3_commandTxt,"APOP"));<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break;</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case "TOP":<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;TOP(Core.GetArgsText(POP3_commandTxt,"TOP"));<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break;<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;default:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;SendData("-ERR Invalid command\r\n");</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//---- Check that maximum bad commands count isn't exceeded ---------------//<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if(m_BadCmdCount &gt; m_pPOP3_Server.MaxBadCommands-1){<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;SendData("421 Too many bad commands, closing transmission channel\r\n");<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return true;<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;m_BadCmdCount++;<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//-------------------------------------------------------------------------//</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break;<br/>&nbsp;&nbsp;&nbsp;&nbsp;<br/>&nbsp;&nbsp;&nbsp;&nbsp;}<br/>&nbsp;&nbsp;&nbsp;}<br/>&nbsp;&nbsp;&nbsp;catch(Exception x)<br/>&nbsp;&nbsp;&nbsp;{<br/>&nbsp;&nbsp;&nbsp;&nbsp;// Connection lost<br/>&nbsp;&nbsp;&nbsp;&nbsp;if(!m_pClientSocket.Connected){<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return true;<br/>&nbsp;&nbsp;&nbsp;&nbsp;}<br/>&nbsp;&nbsp;&nbsp;&nbsp;<br/>&nbsp;&nbsp;&nbsp;&nbsp;SendData("-ERR Unkown temp error\r\n");<br/>&nbsp;&nbsp;&nbsp;&nbsp;m_pPOP3_Server.OnSysError(x,new System.Diagnostics.StackTrace());<br/>&nbsp;&nbsp;&nbsp;}<br/>&nbsp;&nbsp;&nbsp;<br/>&nbsp;&nbsp;&nbsp;return false;<br/>&nbsp;&nbsp;}</p>
<p>===========================<br/>我做了一个pop3接收客户端,在收取邮件时,服务器返回得内容如下:</p>
<p>+OK Return-Path: &lt;com_com@21cn.com&gt;Delivered-To: yysscheng@sina.comReceived: (qmail 32409 invoked from network); 28 Nov 2002 01:31:31 -0000Received: from unknown (HELO 21cn.com) (61.140.60.248)&nbsp; by 202.106.187.186 with SMTP; 28 Nov 2002 01:31:31 -0000Received: from 21cn.com([127.0.0.1]) by 21cn.com(AIMC 2.9.5.6)&nbsp;with SMTP id jm93de57653; Thr, 28 Nov 2002 09:48:55 +0800Received: from 21cn.com([10.2.2.1]) by 21cn.com(AIMC 2.9.5.1)&nbsp;with SMTP id jm73de5e038; Thr, 28 Nov 2002 09:48:55 +0800Content-Type: text/plainContent-Transfer-Encoding: 8BitMIME-Version: 1.0Message-ID: &lt;ow978871906566.19829@webmail1.inner-21cn.com&gt;X-AIMailer: AIMC 2.9.5.6 2002.10.10X-AIMime: MIME/SMIME Lib 2.9 2.9 2002.10.10Date: Thu, 28 Nov 2002 09:34:33 +0800 (CST)From: "??????"&lt;com_com@21cn.com&gt;To: yysscheng &lt;yysscheng@sina.com&gt;Cc: Subject: =?gb2312?b?sOy5q9fUtq+7rw==?=X-Priority: 3X-Originating-IP: 61.163.14.2X-AIMC-AUTH: (null)X-AIMC-MAILFROM: com_com@21cn.com??????&nbsp;&nbsp;&nbsp; ??????????????????????????&nbsp;&nbsp;&nbsp; ??????????&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ??????&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 11.28----------------------------------------------?????????????????????????????????? http://y.21cn.com ????A??210099???????????????????? http://sms.21cn.com/baobei/sjsy.html 21CN??????3??????12??10?????????? http://mail.21cn.com/huodong/9yue/ 21CN????????????????????????U?? http://mail.21cn.com/huodong/11yue/business/ </p>
<p>其中的汉字如何解析出来?<br/>(注:我得连接类如下:<br/>public class Pop3Connection<br/>&nbsp;{<br/>&nbsp;&nbsp;private TcpClient socket;<br/>&nbsp;&nbsp;private StreamReader reader;<br/>&nbsp;&nbsp;private StreamWriter writer;<br/>&nbsp;&nbsp;private bool connected;<br/>&nbsp;&nbsp;public bool Connected<br/>&nbsp;&nbsp;{<br/>&nbsp;&nbsp;&nbsp;get{return connected;}<br/>&nbsp;&nbsp;}<br/>&nbsp;&nbsp;public Pop3Connection()<br/>&nbsp;&nbsp;{<br/>&nbsp;&nbsp;&nbsp;// TODO: 在此处添加构造函数逻辑<br/>&nbsp;&nbsp;&nbsp;connected=false;<br/>&nbsp;&nbsp;&nbsp;socket=new TcpClient();<br/>&nbsp;&nbsp;}<br/>&nbsp;&nbsp;~Pop3Connection()<br/>&nbsp;&nbsp;{<br/>&nbsp;&nbsp;&nbsp;socket=null;<br/>&nbsp;&nbsp;}<br/>&nbsp;&nbsp;internal void Open(string host,int port)<br/>&nbsp;&nbsp;{<br/>&nbsp;&nbsp;&nbsp;if(host==null || host.Trim()=="")<br/>&nbsp;&nbsp;&nbsp;{<br/>&nbsp;&nbsp;&nbsp;&nbsp;throw new ArgumentException("Host is null!");<br/>&nbsp;&nbsp;&nbsp;}<br/>&nbsp;&nbsp;&nbsp;if(port&lt;0)<br/>&nbsp;&nbsp;&nbsp;{<br/>&nbsp;&nbsp;&nbsp;&nbsp;throw new ArgumentException("Port is invalid!");<br/>&nbsp;&nbsp;&nbsp;}<br/>&nbsp;&nbsp;&nbsp;try<br/>&nbsp;&nbsp;&nbsp;{</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;socket.Connect(host,port);<br/>&nbsp;&nbsp;&nbsp;&nbsp;reader=new StreamReader(socket.GetStream(),System.Text.Encoding.ASCII );<br/>&nbsp;&nbsp;&nbsp;&nbsp;writer=new StreamWriter(socket.GetStream(),System.Text.Encoding.ASCII);<br/>&nbsp;&nbsp;&nbsp;&nbsp;connected=true;<br/>&nbsp;&nbsp;&nbsp;}<br/>&nbsp;&nbsp;&nbsp;catch(Exception e)<br/>&nbsp;&nbsp;&nbsp;{<br/>&nbsp;&nbsp;&nbsp;&nbsp;connected=false;<br/>&nbsp;&nbsp;&nbsp;}<br/>&nbsp;&nbsp;}<br/>&nbsp;&nbsp;internal void SendCommand(string cmd)<br/>&nbsp;&nbsp;{<br/>&nbsp;&nbsp;&nbsp;writer.WriteLine(cmd);<br/>&nbsp;&nbsp;&nbsp;writer.Flush();<br/>&nbsp;&nbsp;}<br/>&nbsp;&nbsp;internal void GetReply(out string reply )<br/>&nbsp;&nbsp;{<br/>&nbsp;&nbsp;&nbsp;if(Connected)<br/>&nbsp;&nbsp;&nbsp;{reply=reader.ReadLine();}<br/>&nbsp;&nbsp;&nbsp;else<br/>&nbsp;&nbsp;&nbsp;{reply="";}<br/>&nbsp;&nbsp;}<br/>&nbsp;&nbsp;internal void Close()<br/>&nbsp;&nbsp;{<br/>&nbsp;&nbsp;&nbsp;reader.Close();<br/>&nbsp;&nbsp;&nbsp;writer.Flush();<br/>&nbsp;&nbsp;&nbsp;writer.Close();<br/>&nbsp;&nbsp;&nbsp;reader=null;<br/>&nbsp;&nbsp;&nbsp;writer=null;<br/>&nbsp;&nbsp;&nbsp;socket.Close();<br/>&nbsp;&nbsp;&nbsp;connected=false;<br/>&nbsp;&nbsp;}<br/>&nbsp;}<br/>)</p>
<p></font>&nbsp;</p>
0
2008-12-31 16:48:17   评论 分享淘帖

只有小组成员才能发言,加入小组>>

135个成员聚集在这个小组

加入小组

创建小组步骤

关闭

站长推荐 上一条 /7 下一条

快速回复 返回顶部 返回列表