简单邮件客户端

时间:2014-04-19 19:00:28

标签: c# streamreader 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 
        StreamWriter sw = new StreamWriter(sslstream);
        // Assigned reader to stream
        StreamReader reader = new StreamReader(sslstream);
        // refer POP rfc command, there very few around 6-9 command
        sw.Write("USER my_login@gmail.com\r\n");
        // sent to server
        sw.Flush();
        sw.Write("PASS my_pass\r\n");
        sw.Flush();

        // this will retrive your first email
        sw.Write("LIST\r\n");
        sw.Flush();

        // close the connection
        sw.WriteLine("QUIT\r\n");
        sw.Flush();

        richTextBox2.Text = reader.ReadToEnd();

        sw.Close();
        reader.Close();
        tcpclient.Close();

我不明白为什么只有在发送命令QUIT后才能从流中读取?如果我在发送消息QUIT之前尝试读取流结束或流中的所有行,则程序崩溃。任何人都可以帮助我吗?

非常感谢!

1 个答案:

答案 0 :(得分:2)

您的程序不会崩溃,它会挂起。它挂起,因为ReadToEnd()等待服务器发送的EOF,直到连接关闭。