How to validate the right email address format in PHP?

Receiving email messages via your website or web application is an important feature and often the only way to get in contact with your customers. If you look back, how often have you got an email message from a potential customer with an invalid or wrong email address? Sure you can use advanced regular expression patterns to check the email address format, but these patterns doesn’t check if the email address really exists. This tutorial is about a double email address validation, first we check the email address format and second we validate the email addresses with an API system in PHP.

In what kind of situations should you double check an email address?

Actually you need a valid email address all the time, but sometimes an additional check is necessary to reach your goals. We use a second layer of email address validation for:

  • Contact forms – Most contact forms include only the necessary form fields like name, email address and the message. There is no chance to contact your new lead if the submitted email address is wrong.
  • Web shop orders – In this case you you get (often) much more information, but your customer will never get an order conformation if the email address he entered during the checkout isn’t valid.
  • Mailing lists – If your mailing list wasn’t used for some time, a lot of the included email addresses might be expired in the meantime. The next email campaign might have a high bounce rate and this is often a problem for your email marketing provider. Check all the email addresses before you send out a new campaign. Check the bonus PHP function below!

Validate more with the Mailboxlayer API

Mailboxlayer is a service from apilayer, a company based in Vienna, Austria. They offer not only the email validation API, but also API systems for the conversion of currencies, PDF creation and several more. All their API services are based on a premium model, so you can use them for free if you don’t make so much API calls.

A free Mailboxlayer API account includes 250 credits per month. This might be enough for smaller sites, but only if you submit only those addresses with a “good” email address format. Use for example a regular expression test before you submit the email address to the API endpoint. Don’t have an account yet? Create your free API account here.

What kind of validation methods are used by Mailboxlayer

Besides a check on the email address format, Mailboxlayer is using different methods to check your submitted email address:

  • DNS validation – A valid MX record is required to send a mail message. If the MX record for the used domain name doesn’t exists, no email message can be delivered.
  • SMTP check – The Mailboxlayer API will create a SMTP connection to verify that a simple HELO  command is possible.
  • Catch all email address – A catch all email address accepts any email address for the used domain name. If your email address check is used for a mailing list, a catch all email address might have a low email open rate.
  • General and disposable email addresses – Mailboxlayer is also able to recognize general email addresses like support, info or contact@domain.com. Those email addresses and also disposable address like user123@domain.com might perform with a low email open rate while sending an email campaign to your mailing list.
  • Valid syntax – Just like in your own application, the API will check the syntax of your email address first (to safe validation time and resources).

How to (pre) check the email address format?

There are different ways to check the email address format. We suggest to check the email address first on the client side in JavaScript and second in PHP as well. Use the functie to validate the email address forma. This way only the “good” formatted email addresses need to be processed by your PHP function.

function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
	return pattern.test(emailAddress);
}
jQuery(document).ready(function($) {
    $( "#testform" ).submit(function( event ) {
        var email = $('#email_address').val();
        if (!isValidEmailAddress(email)) {
            alert( 'Email address ' + email + ' is not valid...' );
        }
        event.preventDefault();
    });
});

If you don’t like to use JavaScript for the client side validation, it’s also a good idea to use HTML5 form field validation. Check the “pattern” attribute where a regular expression is used to validate the form field value. And of course you can use HTML5 also to set a required field.

<form action="email_processor.php">
  <label for="email_address>Email address</label>
  <input type="email" id="email_address" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$">
  <button type="submit">Submit form</button>
</form>

Setup your PHP email validation (test) script

You can use the Mailboxlayer email validation API with any programming language that can parse a JSON formatted data response. Visit the documentation page for the code examples, error codes and any other information your need. For this tutorial we will use the PHP example. Create a new PHP file and add the following code:

<?php
$access_key = 'YOUR_ACCESS_KEY';
$email_address = 'test@domain.com';

$ch = curl_init('http://apilayer.net/api/check?access_key='.$access_key.'&email='.$email_address.'');  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json_response = curl_exec($ch);
curl_close($ch);
$result = json_decode($json_response, true);
print_r($result);

Replace the string “YOUR_ACCESS_KEY” with your Mailboxlayer API key and change the email address to something else. Safe your script and run the PHP script in your browser or via the terminal. You will see a response like this:

array
(
    [email] => test@domain.com
    [did_you_mean] => test@hotmail.com
    [user] => test
    [domain] => domain.com
    [format_valid] => 1
    [mx_found] => 1
    [smtp_check] => 1
    [catch_all] =>
    [role] =>
    [disposable] =>
    [free] =>
    [score] => 0.48
)

You may have noticed that the email validation service has provided a suggestion for email addresses hosted by popular email service providers. If you enter “test@domain.com”, the response shows the suggestion “test@hotmail.com” as a possible valid email address. Play a bit with the example to see what kind of response you get for different entries. Notice also the value for “score”, a value bigger than 0.8 is a good value for email marketing campaigns. If you use the collected email addresses only for transactional emails, a value above 0.65 is acceptable.

The following PHP code example will show different message on success or failure:

<?php
$access_key = 'YOUR_ACCESS_KEY';
$email_address = 'test@domain.com';

// Validate the email address always with filter_var($email, FILTER_VALIDATE_EMAIL)) 
// or similar before you create an API request

$ch = curl_init('http://apilayer.net/api/check?access_key='.$access_key.'&email='.$email_address.'');  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json_response = curl_exec($ch);
curl_close($ch);
if ($result = json_decode($json_response, true)) {
	if (floatval($result['score']) >= 0.8) { // or 0.65 for transactional emails
		echo 'The e-mail address '.$result['email'].' is valid.';
	} else {
		echo 'The entered e-mail address isn\'t valid.';
		if ($result['did_you_mean'] != '') echo ' Did you mean "'.$result['did_you_mean'].'"?';
	}
} else {
	echo 'Error, something went wrong';
}

Based on the response you can use this email address validation check for your contact form or email based application.

Client side email address validation using jQuery

I mentioned this already before, you can use the Mailboxlayer API with every programming language which can parse a JSON string. Beside PHP we use a lot of jQuery code for our website projects. Using the following JavaScript (jQuery) code you can check an email address without a page reload.

// set endpoint and your access key
var access_key = 'YOUR_ACCESS_KEY';
var email_address = 'support@apilayer.com';

// verify email address via AJAX call
$.ajax({
    url: 'http://apilayer.net/api/check?access_key=' + access_key + '&email=' + email_address,   
    dataType: 'jsonp',
    success: function(json) {

    // Access and use your preferred validation result objects
    console.log(json.format_valid);
    console.log(json.smtp_check);
    console.log(json.score);
                
    }
});

This jQuery example is a copy right from the Mailboxlayer documentation. While using this code your API key is visible to bots and anyone else who inspects your page’s source code. Use this kind of client side scripts only in intranets or in a local (test) environment. If you need to check an email address using JavaScript, just make an Ajax call to your own PHP script.

Protect your web forms against comment form spam. We do this often by using the reCaptcha service by Google. Without a solid spam protection your free or paid credits are quickly used and that without a result for your business.

Bonus: PHP function to check a list of email addresses

We suggest to re-check the email addresses from your mailing list if your last campaign was sent more than 6 month ago. We do the same for the lists  from our customers too with a small PHP script. We use the Mailboxlayer API for this job.  The Basic Plan subscription with 5000 API requests is only $9.99 a month and you can cancel the subscription every month. Follow these steps to cleanup your mailing list:

  1. Export all your email addresses from Mailchimp or any other email marketing provider you use (you need only one column with the email address. Maybe you need to edit the .csv file using a spreadsheet editor).
  2. Download our PHP script from here and upload the script together with your .csv export file.
  3. Change the name from your .csv file to match the name inside the script and add also your own Mailboxlayer API key.
  4. Run the PHP script using in PHP command line mode (CLI). The script will read your .csv file and checks every email address via the API system. The response from the Mailboxlayer system is added to the file named “emails-checked.csv”.
  5. Download / open the file “emails-checked.csv” in your spreadsheet editor. The email addresses with a low score and/or a missing results for MX and/or SMTP are candidates for a removal from your mailinglist.

What is important about email address validation?

  • Use always a second layer of email address validation if a valid email address is more than important
  • Validate the email address format before you submit the address to Mailboxlayer, to safe API credits
  • Protect always your public web forms with a reCaptcha challenge (other tools like Akismet are okay too)
  • Don’t use your Mailboxlayer API key in public client side code (JavaScript)
  • Check the addresses from your mailing list if your last email campaign was sent more than 6-9 month ago

Published in: PHP Scripts