#Verify an #Email Address with a #DNS #MX lookup in C#
Sending an email to an invalid email address has some bad side effects, the most important being, is that your message is not going through to its intended recipient, and on a larger scale, a bad email counts towards your bounce ratio with your SMTP provider, which in extreme cases can cause legal issues with EU PECR laws.
You can always, verify the format of an email address using a regex, but this has two issues – one, is that new TLD’s like “.museum” or “.家電” might break the regex, and secondly, even if the email is valid. Secondly, some domains are valid, but have no MX record set up to handle email. like “info@testtesttest.com” is going to pass any regex, but “testtesttest.com” has no ability to handle email.
So, here’s a bit of code in C# that verifies the domain part of the email;
public static bool VerifyEmailDomain(string domain)
{
// Install-Package ARSoft.Tools.Net
try
{
var resolver = new DnsStubResolver();
var records = resolver.Resolve<MxRecord>(domain, RecordType.Mx);
return records.Any();
}
catch {
return false;
}
}
Now, unfortunately, it’s not possible to check if bob@gmail.com is valid, even if fred@gmail.com using this technique, however, if it is really important, then you can check gmail accounts against the AvatarAPI.com API – to verify if the Gmail account has a profile attached.
This technique is the basis behind http://www.directtomx.com/ – a email sending API that bypasses intermediary SMTP servers.