In this article, How we can verify if email address exists or not using C#, you can use this c# validate email address code while registering the user on your Web or Desktop application, to check if the email id entered by user really exists or not. So you will get two answers in this article, how to validate email address in c# and how to verify email address exists or not using C#.
We can divide this verification process into two part:
- Validate the email address format
- Verify email address exists or not using third party API
C# email validation (regex expression used)
Let's begin with checking if an email address is valid using regex validation in C#
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
var stringToTest="email@gmail.com";
var stringtoTest2= "NotAValid@h.com";
string pattern = null;
pattern = "^([0-9a-zA-Z]([-\\.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";
//check first string
if (Regex.IsMatch(stringToTest , pattern))
{
Console.WriteLine(stringToTest+ " is Valid Email address ");
}
else
{
Console.WriteLine(stringToTest + " is Not a Valid Email address");
}
//check second string
if (Regex.IsMatch(stringtoTest2 , pattern))
{
Console.WriteLine(stringtoTest2+ " is Valid Email address ");
}
else
{
Console.WriteLine(stringtoTest2 + " is Not a Valid Email address");
}
}
}
Output:
email@gmail.com is Valid Email address
NotAValid@h.com is Not a Valid Email address
Here is the dotnet fiddle link https://dotnetfiddle.net/kDVo4v
Email address validation in asp.net using RegularExpressionValidator
We are still validating email address not verifying it yet, so to do that using RegularExpressionValidator in ASP.NET Forms, we can use the below C# and .aspx code
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="EmailIdValidate.Default" %>
<!DOCTYPE html>
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Your email: " + TextBox1.Text.ToString();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Validate email address using RegularExpressionValidator in ASP.NET</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Red">RegularExpressionValidator: email</h2>
<asp:Label
ID="Label1"
runat="server"
Font-Bold="true"
Font-Italic="true"
Font-Size="Large"
ForeColor="SeaGreen"
>
</asp:Label>
<br /><br />
<asp:Label ID="Label2" runat="server" Text="Email">
</asp:Label>
<asp:TextBox ID="TextBox1" runat="server" >
</asp:TextBox>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator1"
runat="server"
ControlToValidate="TextBox1"
Text="*"
>
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator
ID="RegularExpressionValidator1"
runat="server"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
ControlToValidate="TextBox1"
ErrorMessage="Input valid email address!"
>
</asp:RegularExpressionValidator>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
Text="Submit email"
Font-Bold="true"
ForeColor="DodgerBlue"
OnClick="Button1_Click"
/>
</div>
</form>
</body>
</html>
Output:
Note: You may need to add key <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" /> in Web.Config under configuration->appsettings to avoid error.
Verify email address exists or not using C#
Now, we have found the C# way to validate it, but validation only checks the pattern of the email id, it doesn't provide us perfect result if that user's really exists or not.
So to verify it's details, we can check the if the Domain name has MX Records or not using C#.
Although this will again doesn't gurantee that email id exists and you can send a deliverable email to that particular Email id, but checking MX Record is a good step to understand if the email id really has Mail Exchange Record.
To check if MX records exists using C#, you need to use DNSClient Nuget package.
Once you install DNSClient package in your C# Code, you can then use below code to verify if email address host has valid MX record to accept emails or not.
public bool ValidateMXRecord(string domain, string mail)
{
var lookup = new LookupClient(IPAddress.Parse("8.8.4.4"), IPAddress.Parse("8.8.8.8"));
lookup.Timeout = TimeSpan.FromSeconds(5);
var result = lookup.Query(domain, QueryType.MX);
var records = result.Answers;
if (records.Any())
{
return true;
}
else
{
return false;
}
}
If you want to see live demo of this, you can check here https://www.minify-beautify.com/email-validation-online, you can also check all DNS records for a domain, using this tool, here is the demo for it https://www.minify-beautify.com/dns-lookup-online
Next possible way, is to use https://quickemailverification.com api, which helps us to verify 100 emails daily for free, so you can sign up for it and get your free API key.
Once you sign up on QuickEmailVerification website, you can to "apisettings" in the menu after login and get your api key as shown below
This key will help us in verifying the email-address.
So, for testing purposes, I will be creating a Console App in my Visual Studio, navigate to "File"->"New"->"Project"-> Select the "Console application" , name it, and click "Ok"
In your Program.cs, use the below C# code and replace the "API_Key" with your valid api key and provide the email address to verify
using System;
using System.Net;
using System.IO;
namespace EmailVerifyConsole
{
class Program
{
static void Main(string[] args)
{
try
{
string apiKey = "API_key";
string emailToValidate = "YourEmailToVerify@example.com";
string responseString = "";
string apiURL = "http://api.quickemailverification.com/v1/verify?email=" + WebUtility.UrlEncode(emailToValidate) + "&apikey=" + apiKey;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiURL);
request.Method = "GET";
using (WebResponse response = request.GetResponse())
{
using (StreamReader ostream = new StreamReader(response.GetResponseStream()))
{
responseString = ostream.ReadLine();
}
}
Console.WriteLine(responseString);
Console.ReadKey();
}
catch (Exception ex)
{
//Catch Exception - All errors will be shown here - if there are issues with the API
}
}
}
}
Once your build and execute the application, you will get JSON response as below, if email id is valid
{
"result": "valid",
"reason": "accepted_email",
"disposable": "false",
"accept_all": "false",
"role": "false",
"free": "true",
"email": "YourEmailAddress@gmail.com",
"user": "YourEmailAddress",
"domain": "gmail.com",
"mx_record": "gmail-smtp-in.l.google.com",
"mx_domain": "google.com",
"safe_to_send": "true",
"did_you_mean": "",
"success": "true",
"message": ""
}
otherwise (if email is not valid , example : hasdsad@gmail.uk.com) you will get output as below
{
"result": "invalid",
"reason": "rejected_email",
"disposable": "false",
"accept_all": "false",
"role": "false",
"free": "false",
"email": "hasdsad@gmail.uk.com",
"user": "hasdsad",
"domain": "gmail.uk.com",
"mx_record": "mx0.123-reg.co.uk",
"mx_domain": "123-reg.co.uk",
"safe_to_send": "false",
"did_you_mean": "hasdsad@gmail.com",
"success": "true",
"message": ""
}
In real-world application, you would have to first validate the email-address then verify it, before saving it into your database, as only valid and verified email-address is useful for us.
You can combine both the C# code to validate and verify the email-address, here is the example of it.
using System;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
namespace EmailVerifyConsole
{
class Program
{
static void Main(string[] args)
{
try
{
//email to validate and then verify
var EmailToValidateVerify = "email@gmail.com";
string pattern = null;
pattern = "^([0-9a-zA-Z]([-\\.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";
//Validate email first
if (Regex.IsMatch(EmailToValidateVerify, pattern))
{
Console.WriteLine(EmailToValidateVerify + " is Valid Email address ");
//email validated call API function to verify it now
VerifyEmail(EmailToValidateVerify);
}
else
{
Console.WriteLine(EmailToValidateVerify + " is Not a Valid Email address");
}
}
catch (Exception ex)
{
//Catch Exception - All errors will be shown here - if there are issues with the API
}
}
public static void VerifyEmail(string emailToValidate)
{
//your API key from quick email verification site
string apiKey = "API_Key";
string responseString = "";
string apiURL = "http://api.quickemailverification.com/v1/verify?email=" + WebUtility.UrlEncode(emailToValidate) + "&apikey=" + apiKey;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiURL);
request.Method = "GET";
using (WebResponse response = request.GetResponse())
{
using (StreamReader ostream = new StreamReader(response.GetResponseStream()))
{
responseString = ostream.ReadLine();
}
}
Console.WriteLine(responseString);
Console.ReadKey();
}
}
}
So, in this way we can validate and then verify email address using C# code.