The only way to be 100% certain the email address is valid would be to actually email the customer. We’ll get to that shortly, but first let’s look at another option.
How can we programmatically determine if an email address is valid with a reasonable amount of certainty? One option would be to test the email address using a library like ASPNETMX. ASPNETMX can test the validity of an email address by essentially doing four things for us:
- Check the Syntax of the email address.
- Make sure the domain has a valid MX record associated with it.
- Make sure the correct SMTP server exists by connecting to it.
- Verify the email address is valid by attempting to send a message and stopping at the last moment
It’s the last part that’s interesting. Let’s manually have an SMTP conversation using telnet and look at what’s going on:
telnet sm11.internetmailserver.net 25 Server: 220 sm11.internetmailserver.net Me: HELO MyLocalComputerName SERVER: 250 sm11.internetmailserver.net Hello Me: MAIL FROM:thesender@michaelossou.com Server: 250 OK < thesender @michaelossou.com> Sender ok Me: RCPT TO:therecipient@michaelossou.com Server: 250 OK < therecipient @michaelossou.com> Recipient ok
When sending a regular message, this conversation would continue. The subject, body, etc. of the message are defined and then the message is sent. ASPNETMX goes through only the above steps and disconnects from the server. It’s interested only in the response the server will issue for the recipients email address. If the server replies ‘Ok’, it considers the email address valid. If the response is not ‘Ok’, it will report that to us as well.
Let’s look at a simple example of a console application that takes an email address and uses ASPNETMX to validate the email address.
using aspNetMX; namespace AspNetMxSingleTest { class Program { static void Main(string[] args) { while (true) { MXValidate.LoadLicenseKey("1234-1234-1234-1234"); MXValidate mx = new MXValidate(); MXValidateLevel lvl = MXValidateLevel.NotValid; mx.CheckGreylisting = true; mx.CacheMXTimeOut = new TimeSpan(1, 0, 0); mx.LogInMemory = true; string emailAddress; Console.WriteLine("Enter Email Address:"); emailAddress = Console.ReadLine(); lvl = mx.Validate(emailAddress, MXValidateLevel.Mailbox); Console.WriteLine(lvl.ToString()); Console.WriteLine(mx.GetLog()); } } } }
Now, let’s look at the results.
A more complete option would probably be to actually send an email. The idea being that when it’s time to send a newsletter or some other communication, we use the bounced messages to flag our bad email addresses.
Services like MailGun and SendGrid make this a pretty painless process as they offer APIs to deal with such events. SendGrid even has a Nuget Package to drop their bits into your Visual Studio project. These aren’t the cheapest options, but if you read our post regarding mass email last week, you will see a lot goes into the services they offer.