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

4

66

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?

Korella answered 9/10, 2013 at 2:25 Comment(4)
Yes, send them an email and see if they response. Otherwise no, because spammers.Threedecker
The only reliable way to validate an email address is to send an email to it. Even if you validate the MX record, you can't reliably query the server because most email servers won't respond to the queries. Thank your friendly neighbourhood spammers for this.Costotomy
https://mcmap.net/q/158087/-how-to-check-if-an-email-address-exists-without-sending-an-emailRetroflex
You can't do it 100%. Check out how these people did it. It's about a thorough as you can getUnsocial
O
48

You can't verify (with enough accuracy to rely on) if an email actually exists using just a single PHP method. You can send an email to that account, but even that alone won't verify the account exists (see below). You can, at least, verify it's at least formatted like one

if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
    //Email is valid
}

You can add another check if you want. Parse the domain out and then run checkdnsrr

if(checkdnsrr($domain)) {
     // Domain at least has an MX record, necessary to receive email
}

Many people get to this point and are still unconvinced there's not some hidden method out there. Here are some notes for you to consider if you're bound and determined to validate email:

  1. Spammers also know the "connection trick" (where you start to send an email and rely on the server to bounce back at that point). One of the other answers links to this library which has this caveat

    Some mail servers will silently reject the test message, to prevent spammers from checking against their users' emails and filter the valid emails, so this function might not work properly with all mail servers.

    In other words, if there's an invalid address you might not get an invalid address response. In fact, virtually all mail servers come with an option to accept all incoming mail (here's how to do it with Postfix). The answer linking to the validation library neglects to mention that caveat.

  2. Spam blacklists. They blacklist by IP address and if your server is constantly doing verification connections you run the risk of winding up on Spamhaus or another block list. If you get blacklisted, what good does it do you to validate the email address?

  3. If it's really that important to verify an email address, the accepted way is to force the user to respond to an email. Send them a full email with a link they have to click to be verified. It's not spammy, and you're guaranteed that any responses have a valid address.

Oshaughnessy answered 9/10, 2013 at 3:7 Comment(8)
this don't check if email exist .. it is like regular expression validationHawker
he does not suggest that is does check if the email exists, just that its format is a valid one.Polk
As I said in my answer, there's no foolproof check to see if an email exists. Not every server will tell you an account is invalid if you try to send an email to it and if you start spamming a server with junk test requests it can get you blacklisted (i.e. Spamhaus, etc)Oshaughnessy
this is useless. what if [email protected] is valid and [email protected] is invalid?Urbas
@BarışKURT And what if sss.com happily accepts both and just dumps the non-existent one without telling you? I am continually amazed by the insistence that somehow there's a magical way to determine that email exists for all email. Some servers will tell you if it exists but many will notOshaughnessy
machavity, I've noticed a certain tendency, sadly, on stackoverflow, that if you answer, like you did, with technical truth, that demonstrates that someone else's answer really is a poor one, some so users will downvote you. Or if they believe, wrongly, that what you say is open to debate, sigh. A client has been pestering me lightly about this, and it's kind of sad, they don't want to hear the truth, which is basically what you are saying, so they find various resources that claim to be able to do this, despte the fact you can't do it, which anyone running a email list can tell you.Overlord
By the way, my upvote is not for the simple validation, which anyone should be doing without thinking about it, but rather for correctly observing that you simply can never rely on server responses to determine email account status, if you could, every spammer in the world would use such a method to validate their email databases to avoid sending to dead emails, which costs them money. The fact they do not use these methods, but rely on either server hosted images with query strings, or clicks to links that then validate the email, is actually all you need to see to get that it can't be done.Overlord
FWIW Point number 3 is the true answer. You must force the user to confirm that the email address is valid and they have access to it. Other than that there is pretty much no way of reliably checking email address' validity.Ml
C
48

Update 2023: Today this will get you blocked, if it works at all. See comments.

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.example
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

Curium answered 9/10, 2013 at 5:0 Comment(5)
This script is great, however, when i tested it on outlook, live and hotmail servers the response code 554 appears on emails that exist, and then the script hangs until it is timed outDurtschi
I tried the class and every valid email comes back with "valid, but not exist!"Pointsman
This is technically true, but pratically inadvisable: ISPs (especially Yahoo and Hotmail) know about this and they will block deliveries from you (even to addresses that do exist) if you do this a lot. In short, don't do it.Kenyakenyatta
@SolaOderinde Maybe the email you've checked have a catchall entry. With this entry you can configure that the mail server should redirect every email which isn't catch by an existing email address to this email account. Therefore every syntactical correct email address would be valid for this server even if there isn't a separate mailbox for this email address.Iseabal
Please validate the mail only syntactically using other methods. As of 2023, there should be no reliable technical way to validate the existence of mail addresses (other then sending to it) - if there was, this would be a great way for SPAMmers to SPAM even more.Underset
V
4

I have been searching for this same answer all morning and have pretty much found out that it's probably impossible to verify if every email address you ever need to check actually exists at the time you need to verify it. So as a work around, I kind of created a simple PHP script to verify that the email address is formatted correct and it also verifies that the domain name used is correct as well.

GitHub here https://github.com/DukeOfMarshall/PHP---JSON-Email-Verification/tree/master

<?php

# What to do if the class is being called directly and not being included in a script     via PHP
# This allows the class/script to be called via other methods like JavaScript

if(basename(__FILE__) == basename($_SERVER["SCRIPT_FILENAME"])){
$return_array = array();

if($_GET['address_to_verify'] == '' || !isset($_GET['address_to_verify'])){
    $return_array['error']              = 1;
    $return_array['message']            = 'No email address was submitted for verification';
    $return_array['domain_verified']    = 0;
    $return_array['format_verified']    = 0;
}else{
    $verify = new EmailVerify();

    if($verify->verify_formatting($_GET['address_to_verify'])){
        $return_array['format_verified']    = 1;

        if($verify->verify_domain($_GET['address_to_verify'])){
            $return_array['error']              = 0;
            $return_array['domain_verified']    = 1;
            $return_array['message']            = 'Formatting and domain have been verified';
        }else{
            $return_array['error']              = 1;
            $return_array['domain_verified']    = 0;
            $return_array['message']            = 'Formatting was verified, but verification of the domain has failed';
        }
    }else{
        $return_array['error']              = 1;
        $return_array['domain_verified']    = 0;
        $return_array['format_verified']    = 0;
        $return_array['message']            = 'Email was not formatted correctly';
    }
}

echo json_encode($return_array);

exit();
}

class EmailVerify {
public function __construct(){

}

public function verify_domain($address_to_verify){
    // an optional sender  
    $record = 'MX';
    list($user, $domain) = explode('@', $address_to_verify);
    return checkdnsrr($domain, $record);
}

public function verify_formatting($address_to_verify){
    if(strstr($address_to_verify, "@") == FALSE){
        return false;
    }else{
        list($user, $domain) = explode('@', $address_to_verify);

        if(strstr($domain, '.') == FALSE){
            return false;
        }else{
            return true;
        }
    }
    }
}
?>
Vestigial answered 5/3, 2014 at 16:36 Comment(1)
This does not check if the email exists, but checks if the mx record exists and up, this week do the job github.com/hbattat/verifyEmailGurney
U
1

As of 2023, there should be no reliable technical way to check the existence of mail addresses. If there was, this would be a great way for SPAMmers to SPAM even more, because they easily could scan for valid emails.

The only way is to send opt-in mails. This does not only check if the address exists, but also if it is the correct one for this user. It does not help if the address exists but belongs to someone else. In some countries like Europe this is even legally required.

Underset answered 14/7, 2023 at 8:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.