如何在PHP中发送电子邮件之前验证SMTP凭据?

时间:2012-12-18 19:50:54

标签: php smtp phpmailer

由于很难找到答案,我认为这可能是不可能的。如果是这样,我想确认这是不可能的。

3 个答案:

答案 0 :(得分:4)

使用最新版本的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();

您可能需要更改端口号并启用SSL,具体取决于目标SMTP服务。例如,Gmail 需要 SSL连接。

要启用SSL,请添加$mail->SMTPSecure = 'ssl';


注意:PHPMailer 在失败时抛出异常。例如,用户名/密码不匹配可能会触发异常。为避免在整个页面上打印错误消息,请将该函数包装在try / catch块中。

$validCredentials = false;

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

答案 1 :(得分:1)

这不是不可能的。

您可以自行编程SMTP交互,并在SMTP协议中检查是否接受了凭据。对于该方法,您必须与SMTP服务器进行套接字级通信(例如,使用[PHP套接字]服务1)。

要了解SMTP协议的工作原理,请尝试手动使用Telnet。

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

答案 2 :(得分:0)

PHP mail函数不支持SMTP身份验证。

您可以考虑使用第三方库,例如

http://swiftmailer.org/

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

或者您可以尝试脚本here

相关问题