其他一切都好,但由于某种原因我无法发送电子邮件:
<?php
$msg="";
use PHPMailer\PHPMailer\PHPMailer;
include_once "PHPMailer/PHPMailer.php";
include_once "PHPMailer/Exception.php";
if(isset($_POST['submit'])) {
$subject=$_POST['subject'];
$email=$_POST['email'];
$message=$_POST['message'];
$mail= new PHPMailer();
$mail->AddAddress('[email protected]', 'First Name');
$mail->SetFrom('[email protected]','admin');
$mail->Subject = $subject;
$mail->isHTML(true);
$mail->Body=$message;
if($mail->send())
$msg="Your rmail msg has been send";
else
$msg="mail msg has not been send";
}
?>
$mail->send()
功能始终转到else
部分。我做错了什么?
您没有声明发送邮件的内容,这可能是原因之一。 PHPMailer 实际上并不发送电子邮件,它的设计目的是连接到您的 Web 服务器上可以发送电子邮件的东西,例如:sendmail、postfix、到邮件中继服务的 SMTP 连接等,因此您可能需要声明在您的设置中。
例如,如果您使用网络服务器内置的 sendmail,请在
之后添加此内容$mail = new PHPMailer;
// declare what mail function you are using
$mail->isSendmail();
PHPMailer 还支持其他几个选项,例如 SMTP 和 gmail。请参阅这组最适合您的场景的示例:https://github.com/PHPMailer/PHPMailer/tree/master/examples
另外,这是我的设置方式,不确定 require 或 include_once 是否是最佳的,但我的安装效果很好。另外,我还添加了 SMTP 模块,以便通过 sendmail 使用该模块。
// require php mailer classes
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
// require php mailer scripts
require 'src/Exception.php';
require 'src/PHPMailer.php';
require 'src/SMTP.php';
这就是我个人安装 PHPMailer 的实际工作方式,通过 PHP 实例化,而不是通过 Composer 安装。我使用了 SO 上另一篇文章的答案 - 如何在没有作曲家的情况下使用 PHPMailer?
我相信始终使用花括号是良好的编码习惯。这是参考你的 if/else 语句。
除此之外,我在你的代码中没有看到任何直接跳出并指出问题区域的内容。
请确保所有 $_POST 变量都回显其预期值。
也回显您的消息,以确保它输出您的预期值。
您不希望这些参数中的任何一个为空。
PHPMailer 类具有错误处理功能。我建议您使用 try/catch 块来显示任何可能存在的错误并从那里排除故障。
您也可以使用
$mail->ErrorInfo;
。这将显示 $mail->send()
函数调用后生成的任何错误。我在我的答案中包含了这两个概念。
像这样:
$msg="";
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception; //<---Add this.
//Switch your includes to requires.
require "PHPMailer/PHPMailer.php";
require "PHPMailer/Exception.php";
//require "PHPMailer/SMTP.php"; //If you are using SMTP make sure you have this line.
if(isset($_POST['submit'])) {
try{
$subject =$_POST['subject'];
$email =$_POST['email'];
$message =$_POST['message'];
//$mail = new PHPMailer();
$mail = new PHPMailer(true); //Set to true. Will allow exceptions to be passed.
$mail->AddAddress('[email protected]', 'First Name');
$mail->SetFrom('[email protected]','admin');
$mail->Subject = $subject;
$mail->isHTML(true);
$mail->Body = $message;
if($mail->send()){
$msg="Your email msg has been send";
}else{
$msg="mail msg has not been send";
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
}catch(phpmailerException $e){
echo $e->errorMessage();
}
}
如果您使用 SMTP,您可以尝试使用
$mail->SMTPDebug
设置。可以为您提供一些额外的信息。检查 PHPMailer 文档以获取值及其属性。