[php] How to check if an email address exists without sending an email?

I have come across this PHP code to check email address using SMTP without sending an email.

Has anyone tried anything similar or does it work for you? Can you tell if an email customer / user enters is correct & exists?

This question is related to php email smtp telnet email-validation

The answer is


Other answers here discuss the various problems with trying to do this. I thought I'd show how you might try this in case you wanted to learn by doing it yourself.

You can connect to an mail server via telnet to ask whether an email address exists. Here's an example of testing an email address for stackoverflow.com:

C:\>nslookup -q=mx stackoverflow.com
Non-authoritative answer:
stackoverflow.com       MX preference = 40, mail exchanger = STACKOVERFLOW.COM.S9B2.PSMTP.com
stackoverflow.com       MX preference = 10, mail exchanger = STACKOVERFLOW.COM.S9A1.PSMTP.com
stackoverflow.com       MX preference = 20, mail exchanger = STACKOVERFLOW.COM.S9A2.PSMTP.com
stackoverflow.com       MX preference = 30, mail exchanger = STACKOVERFLOW.COM.S9B1.PSMTP.com

C:\>telnet STACKOVERFLOW.COM.S9A1.PSMTP.com 25
220 Postini ESMTP 213 y6_35_0c4 ready.  CA Business and Professions Code Section 17538.45 forbids use of this system for unsolicited electronic mail advertisements.

helo hi
250 Postini says hello back

mail from: <[email protected]>
250 Ok

rcpt to: <[email protected]>
550-5.1.1 The email account that you tried to reach does not exist. Please try
550-5.1.1 double-checking the recipient's email address for typos or
550-5.1.1 unnecessary spaces. Learn more at
550 5.1.1 http://mail.google.com/support/bin/answer.py?answer=6596 w41si3198459wfd.71

Lines prefixed with numeric codes are responses from the SMTP server. I added some blank lines to make it more readable.

Many mail servers will not return this information as a means to prevent against email address harvesting by spammers, so you cannot rely on this technique. However you may have some success at cleaning out some obviously bad email addresses by detecting invalid mail servers, or having recipient addresses rejected as above.

Note too that mail servers may blacklist you if you make too many requests of them.


In PHP I believe you can use fsockopen, fwrite and fread to perform the above steps programmatically:

$smtp_server = fsockopen("STACKOVERFLOW.COM.S9A1.PSMTP.com", 25, $errno, $errstr, 30);
fwrite($smtp_server, "helo hi\r\n");
fwrite($smtp_server, "mail from: <[email protected]>\r\n");
fwrite($smtp_server, "rcpt to: <[email protected]>\r\n");

I think you cannot, there are so many scenarios where even sending an e-mail can fail. Eg. mail server on the user side is temporarily down, mailbox exists but is full so message cannot be delivered, etc.

That's probably why so many sites validate a registration after the user confirmed they have received the confirmation e-mail.


About all you can do is search DNS and ensure the domain that is in the email address has an MX record, other than that there is no reliable way of dealing with this.

Some servers may work with the rcpt-to method where you talk to the SMTP server, but it depends entirely on the configuration of the server. Another issue may be an overloaded server may return a 550 code saying user is unknown, but this is a temporary error, there is a permanent error (451 i think?) that can be returned. This depends entirely on the configuration of the server.

I personally would check for the DNS MX record, then send an email verification if the MX record exists.


This will fail (amongst other cases) when the target mailserver uses greylisting.

Greylisting: SMTP server refuses delivery the first time a previously unknown client connects, allows next time(s); this keeps some percentage of spambots out, while allowing legitimate use - as it is expected that a legitimate mail sender will retry, which is what normal mail transfer agents will do.

However, if your code only checks on the server once, a server with greylisting will deny delivery (as your client is connecting for the first time); unless you check again in a little while, you may be incorrectly rejecting valid e-mail addresses.


Although this question is a bit old, this service tip might help users searching for a similar solution checking email addresses beyond syntax validation prior to sending.

I have been using this open sourced service for a more in depth validating of emails (checking for mx records on the e-mail address domain etc.) for a few projects with good results. It also checks for common typos witch is quite useful. Demo here.


function EmailValidation($email)
{
    $email = htmlspecialchars(stripslashes(strip_tags($email))); //parse unnecessary characters to prevent exploits
    if (eregi('[a-z||0-9]@[a-z||0-9].[a-z]', $email)) {
        //checks to make sure the email address is in a valid format
        $domain = explode( "@", $email ); //get the domain name
        if (@fsockopen ($domain[1],80,$errno,$errstr,3)) {
            //if the connection can be established, the email address is probably valid
            echo "Domain Name is valid ";
            return true;
        } else {
            echo "Con not a email domian";
            return false; //if a connection cannot be established return false
        }
        return false; //if email address is an invalid format return false
    }
}

<?php

   $email = "someone@exa mple.com";

   if(!filter_var($email, FILTER_VALIDATE_EMAIL))
      echo "E-mail is not valid";
   else
      echo "E-mail is valid";

?>

The general answer is that you can not check if an email address exists event if you send an email to it: it could just go into a black hole.

That being said the method described there is quite effective. It is used in production code in ZoneCheck except that it uses RSET instead of QUIT.

Where user interaction with his mailbox is not overcostly many sites actually test that the mail arrive somewhere by sending a secret number that must be sent back to the emitter (either by going to a secret URL or sending back this secret number by email). Most mailing lists work like that.


Not really.....Some server may not check the "rcpt to:"

http://www.freesoft.org/CIE/RFC/1123/92.htm

Doing so is security risk.....

If the server do, you can write a bot to discovery every address on the server....


Assuming it's the user's address, some mail servers do allow the SMTP VRFY command to actually verify the email address against its mailboxes. Most of the major site won't give you much information; the gmail response is "if you try to mail it, we'll try to deliver it" or something clever like that.


"Can you tell if an email customer / user enters is correct & exists?"

Actually these are two separate things. It might exist but might not be correct.

Sometimes you have to take the user inputs at the face value. There are many ways to defeat the system otherwise.


I can confirm Joseph's and Drew's answers to use RCTP TO: <address_to_check>. I would like to add some little addenda on top of those answers.

Catch-all providers

Some mail providers implement a catch-all policy, meaning that *@mydomain.com will return positive to the RCTP TO: command. But this doesn't necessarily mean that the mailbox "exists", as in "belongs to a human". Nothing much can be done here, just be aware.

IP Greylisting/Blacklisting

Greylisting: 1st connection from unknown IP is blocked. Solution: retry at least 2 times.

Blacklisting: if you send too many requests from the same IP, this IP is blocked. Solution: use IP rotation; Reacher uses Tor.

HTTP requests on sign-up forms

This is very provider-specific, but you sometimes can use well-crafted HTTP requests, and parse the responses of these requests to see if a username already signed up or not with this provider.

Here is the relevant function from an open-source library I wrote to check *@yahoo.com addresses using HTTP requests: check-if-email-exists. I know my code is Rust and this thread is tagged PHP, but the same ideas apply.

Full Inbox

This might be an edge case, but when the user has a full inbox, RCTP TO: will return a 5.1.1 DSN error message saying it's full. This means that the account actually exists!

Disclosure

I run Reacher, a real-time email verification API. My code is written in Rust, and is 100% open-source. Check it out if you want a more robust solution:

Github: https://github.com/amaurymartiny/check-if-email-exists

With a combination of various techniques to jump through hoops, I manage to verify around 80% of the emails my customers check.


Some issues:

  1. I'm sure some SMTP servers will let you know immediately if an address you give them does not exist, but some won't as a privacy measure. They'll just accept whatever addresses you give them and silently ignore the ones that don't exist.
  2. As the article says, if you do this too often with some servers, they will blacklist you.
  3. For some SMTP servers (like gmail), you need to use SSL in order to do anything. This is only true when using gmail's SMTP server to send email.

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to email

Monitoring the Full Disclosure mailinglist require(vendor/autoload.php): failed to open stream Failed to authenticate on SMTP server error using gmail Expected response code 220 but got code "", with message "" in Laravel How to to send mail using gmail in Laravel? Laravel Mail::send() sending to multiple to or bcc addresses Getting "The remote certificate is invalid according to the validation procedure" when SMTP server has a valid certificate How to validate an e-mail address in swift? PHP mail function doesn't complete sending of e-mail How to validate email id in angularJs using ng-pattern

Examples related to smtp

5.7.57 SMTP - Client was not authenticated to send anonymous mail during MAIL FROM error PHPMailer - SMTP ERROR: Password command failed when send mail from my server php function mail() isn't working Gmail Error :The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required "An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP Getting error while sending email through Gmail SMTP - "Please log in via your web browser and then try again. 534-5.7.14" SmtpException: Unable to read data from the transport connection: net_io_connectionclosed How to configure SMTP settings in web.config Send mail via CMD console Mail not sending with PHPMailer over SSL using SMTP

Examples related to telnet

get all keys set in memcached telnet to port 8089 correct command How to send an HTTP request using Telnet What does "\r" do in the following script? Is it possible to use a batch file to establish a telnet session, send a command and have the output written to a file? automating telnet session using bash scripts Test if remote TCP port is open from a shell script Connecting to smtp.gmail.com via command line Creating a script for a Telnet session? How to check if an email address exists without sending an email?

Examples related to email-validation

Email address validation in C# MVC 4 application: with or without using Regex Email address validation using ASP.NET MVC data type attributes Best Regular Expression for Email Validation in C# Email Address Validation in Android on EditText How to validate an email address in PHP Can there be an apostrophe in an email address? How to check for valid email address? How to check edittext's text is email address or not? How to validate an Email in PHP? HTML5 Email input pattern attribute