Sunday 27 March 2016

How to check if Email Id exists in C# using TCP Client : Code with Explanation

Check if Email Id exists in c# using TCPClient


In my last post, I shared code for checking if email Id exists or not using Sockets.

In this post, I will be using TCPClient to interact with Network Stream and reading the response returned by it using Stream Reader , and deciding on the email existence through the response code returned by host on our Network Stream.



  • TCPClient : Just like Socket, it provides methods for connecting, sending and receiving stream data over a network. We have created TCPClient object using host name and port number of host. The constructor will itself attempt connection for TCPClient.
  • GetStream() : Method to obtain NetworkStream. We can use Write and Read methods to send and receive response with the remote host.
It is no different from our previous approach. Using Sockets and TCPClient are doing the same thing, and as TCPClient is a wrapper around the Socket class, so there is no much performance difference.
Developer can opt for any approach.

In the next post :
  • Sending Activation Link email to registered user



How to check if Email id exists in c#

How to Check if Email Id exists or Not

You can validate email id input by your user in application.
Email can be validated using :
1) Socket
2) TcpClient
Both comes with System.Net.Sockets namespace

Here' the code and the explanation :


  • Socket provides properties and methods for network communication, allowing both synchronous and asynchronous data transfer. More about Sockets : Sockets
  • IPAddress[] IPs = Dns.GetHostAddresses(host);
         Gets the I.P address of your host which you are trying to connect with.
         Connecting the socket with port number is very important otherwise it will throw exception.
         More about Socket.Connect : Socket.Connect()

  • NetworkStream : Provides methods for sending and receiving data over Stream sockets. To create instance of NetworkStream, we must provide a connected socket. Once  the network stream is instantiated, we use Write() method to send data to remote host and StreamReader use Read method to receive data arriving from remote host on NetworkStream.
  • dataBuffer = Encoding.ASCII.GetBytes("RCPT TO:<" + emailId + ">" + ctrl);
Here, we pass the email Id which is to be checked. If the ID exists , the remote host returns with 250 code, and if it doesn't , returns 550.

This is how we can check If email Id exists or not.
Note : Your ISP might have block Port 25 to refrain spammers . In that case RCPT to command will return 550 even if EmailId exists.

That is why during registration, most websites send an Activation Link mail which helps them recognize that the email Id is valid. 

In next posts  :
2) How to send Activation Link mail from your application