在没有 Composer 的情况下使用 PHPMailer

Using PHPMailer without Composer

我刚试过这个例子:

// for use PHP Mailer without composer : 

// ex. Create a folder in root/PHPMAILER
// Put on this folder this 3 files find in "src" 
// folder of the distribution : 
// PHPMailer.php , SMTP.php , Exception.php
  
  // include PHP Mailer
  use PHPMailer\PHPMailer\PHPMailer;
  use PHPMailer\PHPMailer\Exception;
  include dirname(__DIR__) .'/PHPMAILER/PHPMailer.php';
  include dirname(__DIR__) .'/PHPMAILER/SMTP.php';
  include dirname(__DIR__) .'/PHPMAILER/Exception.php';

  // i made a function 

   /*
    *
    * Function send_mail_by_PHPMailer($to, $from, $subject, $message);
    * send a mail by PHPMailer method
    * @Param $to -> mail to send
    * @Param $from -> sender of mail
    * @Param $subject -> suject of mail
    * @Param $message -> html content with datas
    * @Return true if success / Json encoded error message if error 
    * !! need -> classes/Exception.php - classes/PHPMailer.php - classes/SMTP.php
    *
    */
    function send_mail_by_PHPMailer($to, $from, $subject, $message){

          // SEND MAIL by PHP MAILER
          $mail = new PHPMailer();
          $mail->CharSet = 'UTF-8';
          $mail->isSMTP(); // Use SMTP protocol
          $mail->Host = 'your_host.com'; // Specify  SMTP server
          $mail->SMTPAuth = true; // Auth. SMTP
          $mail->Username = 'my_mail@your_host.com'; // Mail who send by PHPMailer
          $mail->Password = 'your_passord_of_your_box'; // your pass mail box
          $mail->SMTPSecure = 'ssl'; // Accept SSL
          $mail->Port = 465; // port of your out server
          $mail->setFrom($from); // Mail to send at
          $mail->addAddress($to); // Add sender
          $mail->addReplyTo($from); // Adress to reply
          $mail->isHTML(true); // use HTML message
          $mail->Subject = $subject;
          $mail->Body = $message;

          // SEND
          if( !$mail->send() ){

              // render error if it is
              $tab = array('error' => 'Mailer Error: '.$mail->ErrorInfo );
              echo json_encode($tab);
              exit;
          }
          else{
              // return true if message is send
              return true;
          }

    }
    /*
    *
    * END send_mail_by_PHPMailer($to, $from, $subject, $message)
    * send a mail by PHPMailer method
    *
    */
  
    // use function :
    send_mail_by_PHPMailer($to, $from, $subject, $message);

调用new PHPMailer()时系统报错:

Can't find class PHPMailer.

文件的包含工作正常。怎么了?

您可以尝试 reading the readme(无论如何,这应该是您第一个看到的地方),它告诉您在没有 composer 的情况下加载 PHPMailer 的正确方法。

我预计问题是您使用的是 include 而不是 require,并且 类 加载失败,因此当您尝试创建实例时,它是未定义,给你你看到的错误。如果没有这些文件,您的脚本将无法运行,因此您希望它在无法加载它们时失败。

虽然有一个教训 - 学习使用作曲家并了解它的工作原理。作为 PHP 新手,这是您能做的最好的事情。