gpt4 book ai didi

c# - 如何在 TcpClient 类中使用 SSL

转载 作者:IT王子 更新时间:2023-10-29 04:37:10 25 4
gpt4 key购买 nike

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

我可以连接到 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();
}

但是这段代码无法登录。

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

最佳答案

您必须使用 SslStream连同 TcpClient然后使用 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();

编辑

以上代码将简单地通过 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));

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

关于c# - 如何在 TcpClient 类中使用 SSL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8375013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com