如何在 functions.php 中正确包含 PHPmailer (Wordpress)

How to include PHPmailer in functions.php properly (Wordpress)

我正在尝试在 functions.php

中包含 PHPmailer

我的代码:

add_action('wp_ajax_nopriv_test_mailer', 'test_mailer');

函数test_mailer(){

try {

    require_once(get_template_directory('/includes/mail/PHPMailer.php'));
    require_once(get_template_directory('/includes/mail/Exception.php'));

    $mail = new PHPMailer(true);                              // Passing `true` enables exceptions

    //Server settings
    $mail->SMTPDebug = 4;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'test@gmail.com';                 // SMTP username
    $mail->Password = 'dummypassword!';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('test@gmail.com', 'Mailer Test');
    $mail->addAddress('john.doe@gmail.com', 'John User');     // Add a recipient
    $mail->addReplyTo('test@gmail.com');

    //Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'Here is the subject testing';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}

wp_die();

}

我也尝试将 require_once 排除在 try catch 之外仍然是同样的错误这里是关于错误

的片段

"PHP Fatal error: Uncaught Error: Class 'PHPMailer' not found"

我使用 betheme 模板并将文件 PHPmailer 存储在 betheme/includes/mail。

get_template_directory() returns 主题的绝对路径,不带任何参数。

为您的包括试试这个:

require_once(get_template_directory().'/includes/mail/PHPMailer.php');
require_once(get_template_directory().'/includes/mail/Exception.php');

正如 BA_Webimax 指出的那样,您应该使用 Wordpress 的内置电子邮件功能,尽管由于 WP 依赖过时的 PHP 版本,您最终将使用非常旧的版本PHP用它来邮寄。

回到您当前的问题:失败的不是您的 require_once 语句,而是您没有将命名空间 PHPMailer class 导入到您的命名空间中。在脚本顶部添加这些:

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

或者,在创建实例时使用 FQCN:

$mail = new PHPMailer\PHPMailer\PHPMailer;

请注意,这也适用于 Exception class,因此您需要说:

catch (PHPMailer\PHPMailer\Exception $e) {