我一直在尝试访问我的GMail帐户,以便从我的电子邮件帐户中检索未读电子邮件。但是,我只会执行登录...之后的任何操作都无效。
首先,我连接到服务器,然后发送login命令,最后发送examine命令。问题是接收的响应仅涉及连接和登录。之后,它只是停止等待某些人从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);
}
答案 0 :(得分:2)
我正在寻找这种“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;
}
}
}
答案 1 :(得分:1)
您可能会考虑使用固定的IMAP / SSL库 - 还有一个仍处于活动状态的here。
This alternative不是免费的。
其中一个的基础有source code that might be helpful,因为你想要推出自己的协议处理程序。
答案 2 :(得分:1)
您的问题是您期望来自IMAP服务器的POP响应。 POP会使用.
终止已提取的邮件,并使用以+OK
或-ERR
开头的行响应其他命令。 IMAP没有。您正在使用所有服务器响应然后挂起,等待与您的类似POP的响应解析器匹配的内容。如果检查返回的数据,您应该看到服务器对您的(格式正确的)请求的响应的剩余部分。
服务器有可能向第二和第三个命令发回响应。这可能是因为你试图管道三个请求;也就是说,您在不等待响应的情况下发送请求。服务器是obliged to allow pipelining while in the SELECTED
state,但协议不保证您可以从NOT AUTHENTICATED
状态管道命令。