让我们按照一些步骤来解决这个问题。
1.确保启用错误报告并设置为报告所有错误(使用 .php 文件中的代码)
error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");
2。检查服务器的邮件日志
您的 localhost 应该记录通过它发送电子邮件的所有尝试。这些日志的位置将用户的根目录下的日志。内部将包含服务器报告的与您尝试发送电子邮件相关的错误消息(如果有)。
3。确保您在 localhost 上设置了邮件服务器
如果您在本地工作站上使用 XAMPP 进行开发,您的工作站上可能没有安装电子邮件服务器。没有一个,PHP默认不能发送邮件。
您可以通过安装基本邮件服务器来克服这个问题。对于 Windows,您可以使用 free Mercury Mail。
您也可以使用 SMTP 发送您的电子邮件。请参阅此answer 以重新检查如何执行此操作。
4.检查 mail() 是否返回 true 或 false 消息
请使用下面的代码,让我知道发生了什么。此代码将显示实际的错误消息,我们可以解决此问题。
替换
mail($to, $subject, $message, $headers);
有
$mailReturn = mail($to, $subject, $message, $headers);
print('<pre>');
print_r($mailReturn);
print('</pre>');
exit();
如果上述 3 个步骤完美完成但没有成功,请执行第 4 步。让我知道这段代码打印的内容。
5.用于从 localhost 发送邮件的 SMTP 设置(在 php.ini 中)
如果您使用的是 Gmail,那么您很幸运。 Gmail 允许我们使用他们的 SMTP,前提是您必须使用自己的 用户名 和 密码 对其进行身份验证。要使用 Gmail SMTP,值将如下所示:
//Set the hostname of the mail server
$mail->Host = "smtp.gmail.com";
//enable this if you are using gmail smtp, for mandrill app it is not required
//$mail->SMTPSecure = 'tls';
//Set the SMTP port number - likely to be 25, 465 or 587
$mail->Port = 25;
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication
$mail->Username = "YOUR.ID@GMAIL.COM";
//Password to use for SMTP authentication
$mail->Password = "YOUR_PASSWORD";
或者,如果您不想使用您的 Gmail 帐户,那么我建议您在 Mandrill 创建一个帐户并获取您的 SMTP 主机,用户名和密码。我已经测试了 gmail 和 mandrill,它们的效果都很好。
//Set the hostname of the mail server
$mail->Host = "smtp.mandrillapp.com";
//Set the SMTP port number - likely to be 25, 465 or 587
$mail->Port = 25;
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication
$mail->Username = "YOUR_REGISTER_EMAIL@MANDRILL.COM";
//Password to use for SMTP authentication
$mail->Password = "YOUR_PASSWORD";
确保检查所有变量值并根据需要进行更改。