How to Verify if an Email Address Exists in C# code example
Example: mailbox exists c#
private static void Main(string[] args)
{
var gMail = IsEmailAccountValid("gmail-smtp-in.l.google.com", "[email protected]");
Console.WriteLine($"Gmail account is valid - {gMail.ToString()}");
var live = IsEmailAccountValid("live-com.olc.protection.outlook.com", "[email protected]");
Console.WriteLine($"Live account is valid - {live.ToString()}");
}
private static byte[] BytesFromString(string str)
{
return Encoding.ASCII.GetBytes(str);
}
private static int GetResponseCode(string ResponseString)
{
return int.Parse(ResponseString.Substring(0, 3));
}
private static bool IsEmailAccountValid(string tcpClient, string emailAddress)
{
TcpClient tClient = new TcpClient(tcpClient, 25);
string CRLF = "\r\n";
byte[] dataBuffer;
string ResponseString;
NetworkStream netStream = tClient.GetStream();
StreamReader reader = new StreamReader(netStream);
ResponseString = reader.ReadLine();
dataBuffer = BytesFromString("HELO Hi" + CRLF);
netStream.Write(dataBuffer, 0, dataBuffer.Length);
ResponseString = reader.ReadLine();
dataBuffer = BytesFromString("MAIL FROM:<[email protected]>" + CRLF);
netStream.Write(dataBuffer, 0, dataBuffer.Length);
ResponseString = reader.ReadLine();
dataBuffer = BytesFromString($"RCPT TO:<{emailAddress}>" + CRLF);
netStream.Write(dataBuffer, 0, dataBuffer.Length);
ResponseString = reader.ReadLine();
var responseCode = GetResponseCode(ResponseString);
if (responseCode == 550)
{
return false;
}
dataBuffer = BytesFromString("QUITE" + CRLF);
netStream.Write(dataBuffer, 0, dataBuffer.Length);
tClient.Close();
return true;
}