首页 > 解决方案 > 如何在functions.php中正确包含PHPmailer(Wordpress)

问题描述

我正在尝试将 PHPmailer 包含在 functions.php 中

我的代码:

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 致命错误:未捕获的错误:找不到类 'PHPMailer'”

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

标签: phpwordpressemailphpmailer

解决方案


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

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

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

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

$mail = new PHPMailer\PHPMailer\PHPMailer;

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

catch (PHPMailer\PHPMailer\Exception $e) {

推荐阅读