简体   繁体   中英

How to validate SMTP credentials before sending email in PHP?

Since it's so hard to find an answer, I'm thinking this might be impossible. If so, I'd like confirmation that it's impossible.

There's a very simple way of doing it using recent versions of PHPMailer .

require_once 'phpmailer/class.phpmailer.php';
require_once 'phpmailer/class.smtp.php';

$mail = new PHPMailer(true);
$mail->SMTPAuth = true;
$mail->Username = 'email@example.com';
$mail->Password = 'my_awesome_password';
$mail->Host = 'smtp.example.com';
$mail->Port = 465;

// This function returns TRUE if authentication
// was successful, or throws an exception otherwise
$validCredentials = $mail->SmtpConnect();

You might need to change the port number and enable SSL depending on the targeted SMTP service. Gmail, for instance, requires a SSL connection.

To enable SSL, add $mail->SMTPSecure = 'ssl';


Notice : PHPMailer throws exceptions on failure. A username/password mismatch, for example, might trigger an exception. To avoid error messages getting printed all over your page, wrap the function inside a try/catch block.

$validCredentials = false;

try {
    $validCredentials = $mail->SmtpConnect();
}
catch(Exception $error) { /* Error handling ... */ }

It is not impossible.

You can program the SMTP interaction yourself and check for confirmation in the SMTP protocol that the credentials were accepted. For that approach, you would have to do socket-level communication with the SMTP server (eg using the [PHP Sockets] service 1 ).

To learn how the SMTP protocol works, try doing that with Telnet once by hand.

http://technet.microsoft.com/en-us/library/aa995718(v=exchg.65).aspx

The PHP mail function does not support SMTP authentication.

You could consider a third party library, eg

http://swiftmailer.org/

http://pear.php.net/package/Mail

or maybe you could try the script here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM