I was reading C# 4.0 in a Nutshell by Joseph and Ben Albahari and came across this code in Networking chapter which reads the mails using POP3. POP3 has a defined communication as we all know. When I use the code in the chapter it looks obvious that it should work but it doesn't. This is the code:
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);
}
}
The code is incomplete in the sense that it doesn't download mails. I was just trying to see what is the 1st reponse that we get from Gmail. But unfortunately, the program just stucks at ReadByte
in ReadLine
method. I think I should get this line when I first connect to the gmail:
+OK Hello there.
But my program just hangs. As per this page:
http://mail.google.com/support/bin/answer.py?answer=13287
you have to connect on pop.gmail.com which is exactly what I have done. Can anybody tell me what is missi开发者_高级运维ng?
Note: Do not send me any 3rd party projects to do this sort of this. I know it is very easy using them. But I am just trying to see what happens under the hoods. It would be better for me if you find the bug present in my program itself.
Thanks.
Use SslStream
instead of NetworkStream
as gmail requires 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 requires you to use SSL.
995 port is POP3 over SSL, consider using SslStream.
精彩评论