使用Gmail阅读邮件

时间:2011-08-17 08:20:16

标签: c# email gmail pop3

我正在Joseph和Ben Albahari的Nutshell中阅读C#4.0,并在网络章节中看到了使用POP3读取邮件的代码。众所周知,POP3具有明确的沟通方式。当我使用本章中的代码时,它看起来很明显它应该可以工作,但事实并非如此。这是代码:

private static string ReadLine(Stream stream)
        {
            List<byte> list = new List<byte>();
            while (true)
            {
                int b = stream.ReadByte();
                if (b == 10 || b < 0) break;

                if (b != 13) list.Add( (byte)b);
            }
            return Encoding.UTF8.GetString(list.ToArray());
        }

        private static void SendCommand(Stream stream, string line)
        {
            byte[] byteArr = Encoding.UTF8.GetBytes(line + "\r\n");
            stream.Write(byteArr, 0, byteArr.Length);
            string response = ReadLine(stream);
            if (!response.StartsWith("+OK"))
                throw new Exception("Pop exception: " + response);
        }

        static void Main(string[] args)
        {

            using (TcpClient client = new TcpClient("pop.gmail.com", 995))
            {

                using (NetworkStream stream = client.GetStream())
                {
                    ReadLine(stream);
                }
            }

代码不完整,因为它不下载邮件。我只是想看看我们从Gmail获得的第一个响应是什么。但遗憾的是,该计划只是在ReadByte方法ReadLine中停留。当我第一次连接到gmail时,我想我应该得到这一行:

+OK Hello there.

但我的程序只是挂起。根据这个页面:

http://mail.google.com/support/bin/answer.py?answer=13287

你必须在pop.gmail.com上连接,这正是我所做的。谁能告诉我缺少什么?

注意:不要向我发送任何第三方项目来执行此类操作。我知道使用它们非常容易。但我只是想看看引擎盖下发生了什么。如果你发现我的程序本身存在错误,对我来说会更好。

感谢。

2 个答案:

答案 0 :(得分:2)

使用SslStream代替NetworkStream,因为gmail需要ssl

TcpClient objTcpClient = new TcpClient();
//Connecting to the pop3 server at the specified port 
objTcpClient.Connect(pop3Server, pop3PortNumber);

//ValidateCertificate is a delegate
SslStream netStream = new SslStream(objTcpClient.GetStream(), false, ValidateCertificate); //Authenticates the client on the server
netStream.AuthenticateAsClient(pop3Server);
//Stream Reader to read response stream 
StreamReader netStreamReader = new StreamReader(netStream, Encoding.UTF8, true);

答案 1 :(得分:1)

Gmail要求您使用SSL。

995端口是基于SSL的POP3,请考虑使用 SslStream

相关问题