home *** CD-ROM | disk | FTP | other *** search
- #include "stdafx.h"
- #using <mscorlib.dll>
- #using <system.dll>
-
- using namespace System;
- using namespace System::IO;
- using namespace System::Text;
- using System::Net::Sockets::NetworkStream;
- using System::Net::Sockets::TcpClient;
- using System::IO::StreamReader;
-
- #include "Pop3Client.h"
-
- void CPOP3Client::CPop3Client()
- {
- m_Client = 0;
- m_strPOP3HostName = String::Empty;
- m_strUserName = String::Empty;
- m_strPassword = String::Empty;
- m_strStatus = new String ("OK");
- }
-
- void CPOP3Client::Close()
- {
- if (m_Client) m_Client->Close();
- m_Client = 0;
- }
-
- bool CPOP3Client::ConnectToServer()
- {
- Close(); // Close existing connection.
- m_Client = new TcpClient (m_strPOP3HostName, 110); // Create connection to the server.
- StreamReader * streamRead = new StreamReader (m_Client->GetStream(), Encoding::ASCII ); // Create stream to read.
- String * resp = streamRead->ReadLine(); // read server response
- streamRead->DiscardBufferedData(); // Ignore rest of the buffer.
-
- if (resp->StartsWith("+OK")) return true; // Check response for +OK reply.
- else
- {
- Close();
- return false;
- }
- }
-
- void CPOP3Client::DisconnectFromServer()
- {
- String *strResponse = String::Empty;
- SendCommand("QUIT", &strResponse);
- Close();
- }
-
- bool CPOP3Client::SendCommand (String *strCommand, String** pstrOutput)
- {
- if (m_Client == 0) return false;
-
- // Add crlf to the command.
- String * strRequest = String::Concat(strCommand, "\r\n");
-
- // Create streams to read from socket and write to it.
- NetworkStream * streamWrite = m_Client->GetStream();
- StreamReader * streamRead = new StreamReader(streamWrite, Encoding::ASCII);
-
- // Convert from the string to the byte stream and write to socket.
- Byte outbuffer __gc[] = Encoding::ASCII->GetBytes(strRequest);
- streamWrite->Write(outbuffer, 0, outbuffer->Length);
-
- // read response from the socket.
- *pstrOutput = streamRead->ReadLine();
-
- // Ignore rest of the buffer.
- streamRead->DiscardBufferedData();
-
- return (*pstrOutput)->StartsWith(S"+OK") ? true : false;
- }
-
- int CPOP3Client::MessageCount()
- {
- String *strResponse = String::Empty;
- String *strNrOfMessages;
-
- // Create array of separators to parse response from server.
- Char separator __gc[] = new Char __gc[1];
- separator[0] = ' ';
-
- try
- {
- if(!ConnectToServer ()) return -1;
- if(!SendCommand (String::Concat("USER ", m_strUserName), &strResponse)) return -1;
- if(!SendCommand (String::Concat("PASS ", m_strPassword), &strResponse)) return -1;
- if(!SendCommand ("STAT", &strResponse)) return -1;
-
- // Extract number of messages from the string.
- strNrOfMessages = strResponse->Split(separator)[1];
-
- return Convert::ToInt32(strNrOfMessages);
- }
- catch(Exception* e)
- {
- m_strStatus = String::Concat ("Error: ", e->Message);
- return -1;
- }
- __finally
- {
- DisconnectFromServer();
- }
- }
-