【问题标题】:Using Gmail to read mails使用 Gmail 阅读邮件
【发布时间】:2011-08-17 08:20:16
【问题描述】:

我正在阅读 Joseph 和 Ben Albahari 的 C# 4.0 in a Nutshell,并在使用 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 中得到的第一个回复是什么。但不幸的是,程序只是在ReadLine 方法中停留在ReadByte。我想我第一次连接到 gmail 时应该得到这条线:

+OK Hello there.

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

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

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

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

谢谢。

【问题讨论】:

  • 您是否在 gmail 设置中启用了 pop3?
  • @zenwalker:是的,我已启用,但这与我目前编写的程序无关。至少我应该在那里得到+OK Hello。来自 gmail 的消息。在这一步之后,提供用户名和密码的步骤来了。但我的第一步本身不起作用。
  • 也许检查流是否被打开。调试程序并查看流能够从端口 995 读取什么

标签: c# email gmail pop3


【解决方案1】:

使用 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);

【讨论】:

  • 什么是validatCertificate论证?
  • ValidateCertificate 是一个 RemoteCertificateValidationCallback 委托,返回 true 或 false,查看msdn link 了解更多信息
【解决方案2】:

Gmail 要求您使用 SSL。

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

【讨论】:

    猜你喜欢
    • 2019-05-24
    • 2015-09-15
    • 2018-05-11
    • 2015-06-04
    • 1970-01-01
    • 1970-01-01
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多