使用TcpClient类的邮件客户端

时间:2014-04-16 11:54:52

标签: c# tcpclient pop3

我找到了从邮箱接收邮件的示例:

// create an instance of TcpClient 

            TcpClient tcpclient = new TcpClient();

            // HOST NAME POP SERVER and gmail uses port number 995 for POP 

            tcpclient.Connect("pop.gmail.com", 995);
            // This is Secure Stream // opened the connection between client and POP Server
            System.Net.Security.SslStream sslstream = new SslStream(tcpclient.GetStream());
            // authenticate as client  
            sslstream.AuthenticateAsClient("pop.gmail.com");
            //bool flag = sslstream.IsAuthenticated;   // check flag
            // Asssigned the writer to stream 
            System.IO.StreamWriter sw = new StreamWriter(sslstream);
            // Assigned reader to stream
            System.IO.StreamReader reader = new StreamReader(sslstream);
            // refer POP rfc command, there very few around 6-9 command
            sw.WriteLine("USER your_gmail_user_name@gmail.com");
            // sent to server
            sw.Flush();
            sw.WriteLine("PASS your_gmail_password");
            sw.Flush();
            // this will retrive your first email
            sw.WriteLine("RETR 1");
            sw.Flush();
            // close the connection
            sw.WriteLine("Quit ");
            sw.Flush();
            string str = string.Empty;
            string strTemp = string.Empty;
            while ((strTemp = reader.ReadLine()) != null)
            {
                // find the . character in line
                if (strTemp == ".")
                {
                    break;
                }
                if (strTemp.IndexOf("-ERR") != -1)
                {
                    break;
                }
                str += strTemp;
            }

但我不明白如何在富文本框中打印邮件正文。哪个字符串包含响应?任何人都可以帮助我吗?

非常感谢!

2 个答案:

答案 0 :(得分:0)

根据我在此代码中的理解,邮件应该在str字符串中。 但我认为你应该在退出服务器之前阅读邮件。所以把你的循环放在

之前
        // close the connection
        sw.WriteLine("Quit ");
        sw.Flush();

答案 1 :(得分:0)

正如我在回复你的另一个,几乎相同的问题时写的:如果你希望编写邮件客户端,你真的需要阅读MIME规范和POP3规范。

或者你可以使用一个为你完成大部分艰苦工作的图书馆,例如MimeKitMailKit

你仍然需要至少对MIME有一个基本的了解,但至少你不必为它编写一个解析器(这是非常重要的,因为现实世界中有多少消息没有遵循规范 - 通常是由那些从不打扰实际阅读规范的人写的。)