gpt4 book ai didi

c# - 使用 C# 将 IMAP 命令发送到 GMail

转载 作者:行者123 更新时间:2023-11-30 21:19:17 24 4
gpt4 key购买 nike

我一直在尝试访问我的 GMail 帐户以从我的电子邮件帐户中检索未读的电子邮件。但是,我只执行登录...之后的任何操作均无效。

首先,我连接到服务器,然后发送登录命令,最后发送检查命令。问题是收到的响应仅指连接和登录。之后,它就停止等待从 StreamReader 读取数据。

try
{
// 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);
tcpclient.Connect("imap.gmail.com", 993);
// This is Secure Stream // opened the connection between client and POP Server
SslStream sslstream = new SslStream(tcpclient.GetStream());
// authenticate as client

sslstream.AuthenticateAsClient("imap.gmail.com");

bool flag = sslstream.IsAuthenticated; // check flag
// Asssigned the writer to stream
System.IO.StreamWriter sw = new StreamWriter(sslstream);
// Assigned reader to stream
System.IO.StreamReader reader = new StreamReader(sslstream);

sw.WriteLine("tag LOGIN user@gmail.com pass");
sw.Flush();

sw.WriteLine("tag2 EXAMINE inbox");
sw.Flush();

sw.WriteLine("tag3 LOGOUT ");
sw.Flush();

string str = string.Empty;
string strTemp = string.Empty;
try
{
while ((strTemp = reader.ReadLine()) != null)
{
Console.WriteLine(strTemp);
// find the . character in line
if (strTemp == ".")
{
//reader.Close();
break;
}
if (strTemp.IndexOf("-ERR") != -1)
{
//reader.Close();
break;
}
str += strTemp;
}
}
catch (Exception ex)
{
string s = ex.Message;
}
//reader.Close();

}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

最佳答案

我一直在寻找这种“Hello World”示例来帮助我入门。在 dkarp 的回答的帮助下,这是我对 Miguel 的例子的看法:

        static void Main( string[] args ) {
try {
TcpClient tcpclient = new TcpClient();
tcpclient.Connect( "imap.gmail.com", 993 );

SslStream sslstream = new SslStream( tcpclient.GetStream() );
sslstream.AuthenticateAsClient( "imap.gmail.com" );

if ( sslstream.IsAuthenticated ) {
StreamWriter sw = new StreamWriter( sslstream );
StreamReader sr = new StreamReader( sslstream );

sw.WriteLine( "tag LOGIN user@gmail.com pass" );
sw.Flush();
ReadResponse( "tag", sr );

sw.WriteLine( "tag2 EXAMINE inbox" );
sw.Flush();
ReadResponse( "tag2", sr );

sw.WriteLine( "tag3 LOGOUT" );
sw.Flush();
ReadResponse( "tag3", sr );
}
}
catch ( Exception ex ) {
Console.WriteLine( ex.Message );
}
}

private static void ReadResponse( string tag, StreamReader sr ) {
string response;

while ( ( response = sr.ReadLine() ) != null ) {
Console.WriteLine( response );

if ( response.StartsWith( tag, StringComparison.Ordinal ) ) {
break;
}
}
}

关于c# - 使用 C# 将 IMAP 命令发送到 GMail,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3863381/

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