Validating email addresses exist. (Part 1)

Validation that data typed into a webpage is formatted as an email address is certainly a great start, but shouldn't be the only validation on an email address before you save it into your database. I think we can do one better than a simple or complex Regular Expression (regex). Some people might say "Just make a validation email part of the signup process." And, that isn't a bad idea at all, I just want something a little more interactive or immediate and to not even accept the data into my database unless it has been validated. There are a couple of ways that we might go about this, while I will mention a few ideas; I will only explore one in detail and with code.

Regex for email validation is a good idea, but shouldn't be your only data validation for email addresses.

How can we validate emails before saving data?

These are just a few ideas that I have had over the years, and thought I should at least mention them.

  • Save the signup with a status field set to Pending email, and a create date. This will allow for a cron job of a sort to clean out any requests that have not been fulfilled.
  • Same as previous, except monitor if the email bounces and if so, delete the record immediately. We know that the user didn't receive the email, and we really have no good way to automatically tell them the email is invalid. (At least at this point in the process)
  • Throw caution to the wind, and rely on Regex alone. (Don't do this, please)
  • My Favorite Idea: Create a simple service (JSON response for AJAX) that will query for the MX server, open up a connection to the SMTP server and ask if the email address supplied exists. This is the method we will be exploring today!

First a little overview and setup.

If you want to skip this tutorial and just validate your email addresses, you can just download the complete php script and upload to your server, or just call mine I am hosting. (Some web hosts disable communication on to destination port 25, so this might be needed) My hosted script location will be: http://tazdij.com/hosted/verifyemail.php?email=email%40domain.com

Emails are actually a really simple thing, and aren't to terribly complicated to send or receive. It only really gets complicated when you are trying to do email marketing, sending thousands or hundreds of thousands of emails, while trying to stay out of the spam folder. We are going to keep this really simple and just create a single PHP Script that will accept a url parameter email and return a json encoded response. And in an HTML page we will use jQuery to simplify the AJAX request to the validation script.

Required for this tutorial:

  • HTTPd server of your choice, with PHP

Well I think that is enough information for the first part. I should have the followup and actual code for part 2, online sometime in the next couple weeks.