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

时间:2019-03-04 13:00:16

标签: wordpress phpmailer

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

我的代码:

add_action('wp_ajax_nopriv_test_mailer', 'test_mailer');

function 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中。

2 个答案:

答案 0 :(得分:1)

get_template_directory()返回主题的绝对路径,并且不包含任何参数。

尝试此操作以包括:

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

答案 1 :(得分:1)

正如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) {