如何使localhost发送电子邮件


How to make localhost to send email?

即使按照THIS对php.ini和sedmail.php文件进行了更改,我也无法通过localhost Xampp发送邮件。我在sendmail.php文件中有一个疑问是什么电子邮件&PassWord在此提供;

auth_username=   
auth_password=  

请有人帮我渡过难关。

您可以使用SMTP邮件发送库,并尝试使用该函数从localhost 发送邮件

让我们按照一些步骤来解决这个问题。

1.确保已启用错误报告并设置为报告所有错误(使用.php文件中的代码)

error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");

2.检查服务器的邮件日志

您的localhost应该记录所有通过它发送电子邮件的尝试。这些日志的位置将是用户在日志下的根目录。里面会有服务器报告的与您尝试发送电子邮件有关的错误消息(如果有的话)。

3.确保在localhost上设置了邮件服务器

如果您使用XAMPP在本地工作站上进行开发,则您的工作站上可能未安装电子邮件服务器。如果没有,PHP默认情况下无法发送邮件。

您可以通过安装一个基本的邮件服务器来克服这个问题。对于Windows,您可以使用免费的Mercury Mail。

您也可以使用SMTP发送电子邮件。请参阅此答案以重新检查如何执行此操作。

4.检查邮件()是否返回true或false并显示消息

请使用下面的代码,让我知道发生了什么。此代码将显示实际的错误消息,我们可以解决此问题。

更换

mail($to, $subject, $message, $headers);

使用

$mailReturn = mail($to, $subject, $message, $headers);
print('<pre>');
print_r($mailReturn);
print('</pre>');
exit();

如果以上3个步骤都做得很完美,但没有成功,则按照步骤4进行。让我知道这个代码打印的是什么。

5.SMTP设置(在php.ini中)用于从localhost发送邮件

如果你正在使用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";

确保检查了所有变量的值,并在需要时进行更改。