DEV Community

Cover image for Email Syntax Validation and Existence Verification in PHP
Antonello Zanini for Writech

Posted on • Edited on

Email Syntax Validation and Existence Verification in PHP

Let's assume you collected several emails from your users over time without sending them a verification email. Now, you want to use these emails to contact your users, send a newsletter, or just make sure the emails you collected are valid and exist. In this case, you should find a way to detect invalid and false emails and ask these users to provide you with a valid one. The easiest approach is to send a verification email to each user.

The problem with this a posteriori approach is that you are asking your users to actively perform an action that would not have been necessary if you had sent a verification email after they signed up. Also, many users may be inactive, lazy, or suspicious about the verification link they received. In other terms, sending a verification email to all of them may not be the best approach.

On the contrary, you should consider running a script that validates your emails for you and then contacts only the users with an email that did not pass the test. So, let's see how to build a script to verify if an email is valid and exists in PHP.

How to Validate and Verify an Email in PHP

There are several online services that allow you to verify if an email is syntactically valid and exists. Here, you are going to learn how to validate and verify an email with two approaches. The first one does not involve Composer, while the second one uses a Composer dependency.

Note that none of these methods are perfect. But although they can rarely fail, they still represent an effective approach to validating most of your emails.

Let's get started!

1. Validating emails without Composer

This first approach does not require Composer and is based on SMTP validation. Learn more about how this approach to email existence verification works here.

In detail, you can verify if an email exists according to the SMTP approach by using the SMTP_validateEmail class from the GitHub repo below:

[`https://github.com/semplon/php-smtp-email-validation`](https://github.com/semplon/php-smtp-email-validation)
Enter fullscreen mode Exit fullscreen mode

Even though this is an old project, it still works like a charm. Since this class does not distinguish between syntax fail and existence fail, you need to define a function to verify if an email is syntactically correct in PHP. You can achieve this as follows:

<?php
/**
 * It checks if an email address is syntactically valid
 * @param string $email
 * @return boolean true if it is valid, false otherwise
 */
function validateEmail($email) {
    return (boolean) filter_var($email, FILTER_VALIDATE_EMAIL);
}
Enter fullscreen mode Exit fullscreen mode

The validateEmail() function above uses the filter_var() PHP function to validate an email address. If you pass the FILTER_VALIDATE_EMAIL option filter to it, filter_var() will validate the email address stored in $email from a syntactical point of view and return the filtered data on success, or false on failure. Then the value returned by filter_var() is converted into boolean and finally returned by the validateEmail() function.

Now, you have everything required to validate and verify and email in PHP without Composer. You can achieve this as shown below:

<?php
require_once("vendor/smtp_validateEmail.class.php");

$queryResult = // retrieving the emails with a query ...

while($row = $queryResult->fetch_assoc()) {
    // retrieving the email from the db record
    $email = $row["email"];

    $isValid = validateEmail($email);
    $exists = verifyEmail($email);

    if ($isValid && $exists) {
        // updating your db record by
        // setting that the email is valid and it exists ...
    }
}

function validateEmail($email) {
    return (boolean) filter_var($email, FILTER_VALIDATE_EMAIL);
}

function verifyEmail($email) {
    // converting the the email to validate
    // to an array
    $emails = array($email);

    // an optional sender (e.g. a 10-min email retrieved from https://10minutemail.com/)
    $sender = "rsohocszrsuadrmzme@ttirv.com";

    // initializing the SMTP email validator
    $SMTPValidator = new SMTP_validateEmail();

    // turn off debug messages
    // to avoid seeing the logs related to the SMTP transaction
    $SMTPValidator->debug = false;

    $results = $SMTPValidator->validate($emails, $sender);

    // returning the result extracted from the resulting array
    foreach ($results as $email => $result) {
        return $result;
    }
}
Enter fullscreen mode Exit fullscreen mode

Notice that in the example above, the SMTP_validateEmail class and its sub-folders and files were placed in the vendor folder.

2. Validating emails with Composer

Here, you are going to learn how to use the VerifyEmail PHP library. As stated on the official GitHub page, VerifyEmail lets you verify email addresses for correct syntax and existence.

You can install it with the following Composer command:

composer require "masroore/verifyemail"
Enter fullscreen mode Exit fullscreen mode

The library supports 4 different levels of validations:

  • SyntaxCheck: validates the email address by performing a syntax check.

  • DnsQuery: verifies the email address by checking if the SMTP MX host responsible for email delivery exists by using the domain part of the email address string.

  • SmtpConnection: verifies the email address by testing the connection to the SMTP MX host.

  • SendAttempt: verifies the email address by testing the SMTP connection, sending EHLO/HELO and MAIL FROM commands, and submitting the given email address string in the RCPT TO command. This is the most complete method, and it is the one used by default.

Each of them can be set with the EmailAddressVerifier::validationLevel property defined in the AddressValidationLevel class.

You can use EmailAddressVerifier to validate and verify an email as follows:

<?php
require "vendor/autoload.php";

use VerifyEmail\EmailAddressVerifier;
use VerifyEmail\Utils;

$queryResult = // retrieving the emails with a query ...

while($row = $queryResult->fetch_assoc()) {
    // retrieving the email from the db record
    $email = $row["email"];

    $isValidAndExists = validateAndVerifyEmail($email);

    if ($isValidAndExists) {
        // updating your db record by
        // setting that the email is valid and it exists ...
    }
}

function validateAndVerifyEmail($email) {
    // initializing EmailAddressVerifier
    $verifier = new EmailAddressVerifier();

    // defining the sender (e.g. an 10-min email retrieved from https://10minutemail.com/)
    $verifier->setMailFrom("rsohocszrsuadrmzme@ttirv.com");
    $verifier->setHelloDomain("ttirv.com");
    $verifier->setValidationLevel(AddressValidationLevel::SendAttempt);

    $result = $verifier->verify($email);

    if ($result === AddressValidationLevel::OK) {
        return true;
    } else {
        return false;
    }
}
Enter fullscreen mode Exit fullscreen mode

Again, a few lines of code are enough to validate and verify your emails.

Conclusion

Here, we looked at how to implement a PHP script to validate a list of emails and verify if they exist. This can be achieved in many ways, and in this article, we learned how to do it with an external library and a Composer library. In both cases, a few bunches of lines of code are enough.

Thanks for reading! I hope that you found this article helpful.


The post "Email Syntax Validation and Existence Verification in PHP" appeared first on Writech.

Top comments (0)