2014-04-16 4 views
0

Я пытаюсь получать сообщения из аккаунта gmail, но получаю сообщение об ошибке: host not found.Получать сообщения от gmail

Вот мой код:

 using (TcpClient client = new TcpClient("pop.gmail.com ", 995)) 
     using (NetworkStream n = client.GetStream()) 
     { 
      ReadLine(n);        // Read the welcome message. 
      SendCommand(n, "[email protected]"); 
      SendCommand(n, "my_password"); 
      SendCommand(n, "LIST");     // Retrieve message IDs 
      List<int> messageIDs = new List<int>(); 
      while (true) 
      { 
       string line = ReadLine(n);    // e.g. "1 1876" 
       if (line == ".") break; 
       messageIDs.Add(int.Parse(line.Split(' ')[0])); // Message ID 
      } 

      foreach (int id in messageIDs)   // Retrieve each message. 
      { 
       SendCommand(n, "RETR " + id); 
       string randomFile = Guid.NewGuid().ToString() + ".eml"; 
       using (StreamWriter writer = File.CreateText(randomFile)) 
        while (true) 
        { 
         string line = ReadLine(n);  // Read next line of message. 
         if (line == ".") break;   // Single dot = end of message. 
         if (line == "..") line = "."; // "Escape out" double dot. 
         writer.WriteLine(line);   // Write to output file. 
        } 
       SendCommand(n, "DELE " + id);  // Delete message off server. 
      } 
      SendCommand(n, "QUIT"); 
     } 

     static void SendCommand(Stream stream, string line) 
     { 
      byte[] data = Encoding.UTF8.GetBytes(line + "\r\n"); 
      stream.Write(data, 0, data.Length); 
      string response = ReadLine(stream); 
      if (!response.StartsWith("+OK")) 
       throw new Exception("POP Error: " + response); 
     } 

Где моя ошибка? Также я хочу удалить некоторые сообщения из моего окна. Как я могу это сделать?

спасибо!

+0

В какой строке появляется ошибка? –

+1

Почему в конце 'pop.gmail.com' есть лишние пробелы? – Yahya

+1

@Yahya, спасибо! Я удалил его, но ошибка осталась – user3443227

ответ

0

Первой проблемой, которую я вижу с вашим кодом, является то, что он не использует SslStream (необходимый для подключения к сервису POP3 с SSL-соединением GMail на порту 995).

Вторая проблема, которую я вижу, это

if (line == "..") line = "."; 

Если вы на самом деле потрудился прочитать POP3 specification, вы откроете для себя это:

Responses to certain commands are multi-line. In these cases, which 
are clearly indicated below, after sending the first line of the 
response and a CRLF, any additional lines are sent, each terminated 
by a CRLF pair. When all lines of the response have been sent, a 
final line is sent, consisting of a termination octet (decimal code 
046, ".") and a CRLF pair. If any line of the multi-line response 
begins with the termination octet, the line is "byte-stuffed" by 
pre-pending the termination octet to that line of the response. 
Hence a multi-line response is terminated with the five octets 
"CRLF.CRLF". When examining a multi-line response, the client checks 
to see if the line begins with the termination octet. If so and if 
octets other than CRLF follow, the first octet of the line (the 
termination octet) is stripped away. If so and if CRLF immediately 
follows the termination character, then the response from the POP 
server is ended and the line containing ".CRLF" is not considered 
part of the multi-line response. 

Это важный бит: При рассмотрении многопрофильным -line, клиент проверяет, начинается ли строка с октета завершения. Если это так и если последуют октеты, отличные от CRLF, первый октет строки (октет завершения) удаляется.

Это означает, что если клиент сталкивается с линией, такой как «.. some text \ r \ n», ведущий «.» необходимо удалить.

Ваш код только удаляет его, если строка точно соответствует «.. \ r \ n».

+0

ОК. Большое спасибо! – user3443227