如何在TcpClient类中使用SSL

Md *_*ker 20 .net c# email tcpclient

在.NET框架中,有一个类TcpClient可以从电子邮件服务器中检索电子邮件.本TcpClient类有4个构造与内搭最多两个参数的服务器连接.它适用于那些不使用SSL的服务器.但是gmail或许多其他电子邮件提供商使用SSL进行IMAP.

我可以连接gmail服务器但无法使用email_id和密码进行身份验证.

我的验证用户代码是

public void AuthenticateUser(string username, string password)
{
    _imapSw.WriteLine("$ LOGIN " + username + " " + password);
    //_imapSw is a object of StreamWriter class
    _imapSw.Flush();
    Response();
}
Run Code Online (Sandbox Code Playgroud)

但是这段代码无法登录.

那么TcpClient当我必须使用SSL时,如何使用该类来检索电子邮件?

cod*_*ger 41

您必须使用SslStreamTcpClient,然后使用SslStream来读取数据而不是TcpClient.

有点像:

        TcpClient mail = new TcpClient();
        SslStream sslStream;

        mail.Connect("pop.gmail.com", 995);
        sslStream = new SslStream(mail.GetStream());

        sslStream.AuthenticateAsClient("pop.gmail.com");

        byte[] buffer = new byte[2048];
        StringBuilder messageData = new StringBuilder();
        int bytes = -1;
        do
        {
            bytes = sslStream.Read(buffer, 0, buffer.Length);

            Decoder decoder = Encoding.UTF8.GetDecoder();
            char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
            decoder.GetChars(buffer, 0, bytes, chars, 0);
            messageData.Append(chars);

            if (messageData.ToString().IndexOf("<EOF>") != -1)
            {
                break;
            }
        } while (bytes != 0);

        Console.Write(messageData.ToString());
        Console.ReadKey();
Run Code Online (Sandbox Code Playgroud)

编辑

以上代码只需通过SSL连接到Gmail并输出测试邮件的内容即可.要登录Gmail帐户并发出命令,您需要执行以下操作:

        TcpClient mail = new TcpClient();
        SslStream sslStream;
        int bytes = -1;

        mail.Connect("pop.gmail.com", 995);
        sslStream = new SslStream(mail.GetStream());

        sslStream.AuthenticateAsClient("pop.gmail.com");

        byte[] buffer = new byte[2048];
        // Read the stream to make sure we are connected
        bytes = sslStream.Read(buffer, 0, buffer.Length);
        Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, bytes));

        //Send the users login details
        sslStream.Write(Encoding.ASCII.GetBytes("USER USER_EMAIL\r\n"));
        bytes = sslStream.Read(buffer, 0, buffer.Length);
        Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, bytes));

        //Send the password                        
        sslStream.Write(Encoding.ASCII.GetBytes("PASS USER_PASSWORD\r\n"));
        bytes = sslStream.Read(buffer, 0, buffer.Length);
        Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, bytes));

        // Get the first email 
        sslStream.Write(Encoding.ASCII.GetBytes("RETR 1\r\n"));
        bytes = sslStream.Read(buffer, 0, buffer.Length);
        Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, bytes));
Run Code Online (Sandbox Code Playgroud)

显然,没有所有重复的代码:)