C# 使用Gmail阅读邮件
我在阅读Joseph和Ben Albahari编写的C#4.0简而言之,在网络一章中遇到了这段代码,该章使用POP3阅读邮件。众所周知,POP3有一个定义的通信。当我使用本章中的代码时,很明显它应该可以工作,但事实并非如此。代码如下:C# 使用Gmail阅读邮件,c#,email,gmail,pop3,C#,Email,Gmail,Pop3,我在阅读Joseph和Ben Albahari编写的C#4.0简而言之,在网络一章中遇到了这段代码,该章使用POP3阅读邮件。众所周知,POP3有一个定义的通信。当我使用本章中的代码时,很明显它应该可以工作,但事实并非如此。代码如下: private static string ReadLine(Stream stream) { List<byte> list = new List<byte>(); whil
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);
}
}
但是我的程序挂起了。根据本页:
你必须连接pop.gmail.com,这正是我所做的。谁能告诉我少了什么
注意:不要向我发送任何第三方项目来执行此类操作。我知道使用它们很容易。但我只是想看看遮光罩下会发生什么。如果你能在我的程序中发现这个bug,对我来说会更好
谢谢。Gmail要求您使用SSL
995端口是在SSL上的POP3,考虑使用<强> SSLFiels.< /P> < P>使用<代码> SSLFase而不是<代码> NETWorkStudio > 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);
你在gmail设置中输入pop3了吗?@zenwalker:是的,我已经启用了,但这与我目前编写的程序无关。至少我应该得到+好,你好。来自gmail的消息。在这个步骤之后,提供用户名和密码的步骤就来了。但我的第一步本身不起作用。也许可以检查流是否被打开。调试程序并查看流能够从端口995读取什么内容ValidateCertificate参数是什么?ValidateCertificate是一个RemoteCertificateValidationCallback委托,返回true或false,请检查以了解更多信息
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);