static bool ValidateEmailAccount(string server, int port, string userName, string password, out string ErrorMessage)
{
ErrorMessage = "";
//create a tcp connection
TcpClient _server = new TcpClient(server, port);
//prepare
NetworkStream netStream = _server.GetStream();
StreamReader reader = new StreamReader(_server.GetStream());
if (!reader.ReadLine().Contains("+OK"))
{
//失敗
ErrorMessage = "server鏈接失敗";
return false;
}
string data;
byte[] charData;
string CRLF = "\r\n";
//login
data = "USER " + userName + CRLF;
charData = System.Text.Encoding.ASCII.GetBytes(data);
netStream.Write(charData, 0, charData.Length);
if (!reader.ReadLine().Contains("+OK"))
{
//賬戶錯誤
ErrorMessage = "賬戶錯誤";
return false;
}
data = "PASS " + password + CRLF;
charData = System.Text.Encoding.ASCII.GetBytes(data);
netStream.Write(charData, 0, charData.Length);
if (!reader.ReadLine().Contains("+OK"))
{
//密碼錯誤
ErrorMessage = "密碼錯誤";
return false;
}
return true;
}
調用
string errorMessage;
bool isContains = ValidateEmailAccount("pop3.163.com", 110, "[email protected]", "************", out errorMessage);
Console.WriteLine(isContains ? "用戶存在" : errorMessage);
摘自 sandy的專欄