php - 如何在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 中。
解决方案
正如 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) {
推荐阅读
- scikit-learn - TypeError:“OneHotEncoder”对象不可迭代
- python - 如何在 Django 中为几乎相同的 CreateView 视图创建两个并行的 ListView
- reactjs - 如何将邮件保存为pdf格式
- python - 找不到型号“en”。看起来您正在尝试从快捷方式加载模型,该快捷方式在 spaCy v3.0 中已过时
- laravel - 带有 vue3 apollo 和复杂 where 的类型化文档节点
- database - 具有不同客户端(数据库)的 MVC 5 Web 应用程序
- excel - 如何使用 Find 函数查找值?
- amazon-web-services - 为 K8S 上的应用程序安装 NVIDIA 驱动程序
- javascript - Jquery倒计时计数器无法正常工作
- python - 与标准 Python 列表或数组等效的 NumPy 索引数组