Error: Class 'PHPMailer' not found

Error: Class 'PHPMailer' not found

错误:致命错误:未捕获错误:在 C:\xampp\htdocs\php-mailer\index.php:4 中未找到 Class 'PHPMailer' 堆栈跟踪:抛出 #0 {main}在 C:\xampp\htdocs\php-mailer\index.php 第 4 行

我的 PHP 代码在这里:

require("src/PHPMailer.php");
require("src/Exception.php");
$mail = new PHPMailer();  

$mail->IsSMTP();                                      
$mail->Host = 'smtp.gmail.com'; 
$mail->SMTPAuth = true;     // turn on SMTP authentication
$mail->Username = "gmail id";  // SMTP username
$mail->Password = "mypassword"; // SMTP password

$mail->From = "opensourcesivaprakash@gmail.com";
$mail->FromName = "Mailer";
$mail->AddAddress("siva.sing.sivan@gmail.com", "Josh Adams");
$mail->AddAddress("sp");                  // name is optional
//$mail->AddReplyTo("opensourcesivaprakash@gmail.com", "Information");

$mail->WordWrap = 50;                                 // set word wrap to 50 characters
//$mail->AddAttachment("/var/tmp/file.tar.gz");         // add attachments
//$mail->AddAttachment("/tmp/image.jpg", "new.jpg");    // optional name
$mail->IsHTML(true);                                  // set email format to HTML

$mail->Subject = "Here is the subject";
$mail->Body    = "This is the HTML message body in bold!";
$mail->AltBody = "This is the body in plain text for non-HTML mail clients";

if(!$mail->Send())
{
   echo "Message could not be sent. 
";
   echo "Mailer Error: " . $mail->ErrorInfo;
   exit;
}

echo "Message has been sent";

请让我知道我在此处的代码中犯了什么错误。

是因为你没有考虑PHPMailer的命名空间。做以下两件事之一:

更改您的实例化以使用完全限定的 class 名称 (FQCN):

$mail = new PHPMailer\PHPMailer\PHPMailer();

或者,在加载 classes 之前,在文件顶部定义导入:

use PHPMailer\PHPMailer\PHPMailer;

这将使您现有的 new PHPMailer 线路正常工作。

PHPMailer 提供的所有示例都使用后一种方法,并且在故障排除指南中也有描述。

将文件复制到 src\ 文件夹,并在您的代码中使用以下内容:

require "src\Exception.php";
require "src\PHPMailer.php";
require "src\SMTP.php";

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

try { 
    //your code
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}