How to validate SMTP credentials before sending email in PHP?

江枫思渺然 提交于 2019-12-12 14:14:34

问题


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.


回答1:


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 (e.g. using the [PHP Sockets] service1).

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




回答2:


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 ... */ }



回答3:


The PHP mail function does not support SMTP authentication.

You could consider a third party library, e.g.

http://swiftmailer.org/

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

or maybe you could try the script here



来源:https://stackoverflow.com/questions/13940424/how-to-validate-smtp-credentials-before-sending-email-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!