how to check if a mailbox exists 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();

  /* Perform HELO to SMTP Server and get Response */
  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();

  /* Read Response of the RCPT TO Message to know from google if it exist or not */
  dataBuffer = BytesFromString($"RCPT TO:<{emailAddress}>" + CRLF);
  netStream.Write(dataBuffer, 0, dataBuffer.Length);
  ResponseString = reader.ReadLine();
  var responseCode = GetResponseCode(ResponseString);

  if (responseCode == 550)
  {
    return false;
  }

  /* QUITE CONNECTION */
  dataBuffer = BytesFromString("QUITE" + CRLF);
  netStream.Write(dataBuffer, 0, dataBuffer.Length);
  tClient.Close();
  return true;
}