How to check if an email address is real or valid using PHP

telexper picture telexper · Oct 9, 2013 · Viewed 165.1k times · Source

I found some websites that claim to verify if email addresses are valid. Is it possible to check if an email address is valid using just PHP?

<?php
    if($_POST['email'] != ''){
        // The email to validate
        $email = $_POST['email'];

        // An optional sender
        function domain_exists($email, $record = 'MX'){
            list($user, $domain) = explode('@', $email);
            return checkdnsrr($domain, $record);
        }
        if(domain_exists($email)) {
            echo('This MX records exists; I will accept this email as valid.');
        }
        else {
            echo('No MX record exists;  Invalid email.');
        }
    }
?>
<form method="POST">
    <input type="text" name="email">
    <input type="submit" value="submit">
</form>

This is what I have right now. It checks if the domain exist, but it cannot check if the user's email exist on that domain. Is it possible to do that using PHP?

Answer

Mohsen Alizadeh picture Mohsen Alizadeh · Oct 9, 2013

You should check with SMTP.

That means you have to connect to that email's SMTP server.

After connecting to the SMTP server you should send these commands:

HELO somehostname.com
MAIL FROM: <[email protected]>
RCPT TO: <[email protected]>

If you get "<[email protected]> Relay access denied" that means this email is Invalid.

There is a simple PHP class. You can use it:

http://www.phpclasses.org/package/6650-PHP-Check-if-an-e-mail-is-valid-using-SMTP.html