Can I check if an email address exists using .net?

Viewed 65030

Ive seen some php examples of how you can ping an inbox(without sending any mail to it) to check whether it exists. I was wondering if anyone knows if this is possible with .net? If it is Im going to write an app to do a bulk check on list of emails i have captured through my site.

7 Answers

​ 1. Get the MX record for the email provider by using following command:

nslookup -type=mx gmail.com
  1. Make call to tcp client to check if email is valid:

    private static void Main(string[] args)
    {            
      var gMail = IsEmailAccountValid("gmail-smtp-in.l.google.com", "aa.aa@gmail.com");
      Console.WriteLine($"Gmail account is valid - {gMail.ToString()}");
    
      var live = IsEmailAccountValid("live-com.olc.protection.outlook.com", "aa.aa@live.com");
      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:<YourGmailIDHere@gmail.com>" + 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;
    }
    

The MX record can be obtained using code:

var lookup = new LookupClient();
var result = lookup.QueryAsync("gmail.com", QueryType.ANY).Result;
var domainName = result.Additionals[result.Additionals.Count - 1].DomainName.Value;

Using above code find the MX lookup and use that MX lookup to check if email is valid or not.

​

Related