You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

手动安装PHPMailer时smtpSend报错:未定义常量PHPMailer

问题:PHPMailer调用send()时触发"Undefined constant"致命错误

在PHP 8.0.8环境下手动安装PHPMailer 6.8.0,采用SMTP方式发送邮件时,调用send()方法触发致命错误:

Undefined constant "PHPMailer\PHPMailer\PHPMailer"

错误出现在PHPMailer文件第2017行:

$header = PHPMailer . phpstatic::stripTrailingWSP($header) . static::$LE . static::$LE;

文件结构说明:PHPMailer放置在src目录下的PHPMailer文件夹中,调用它的emailer.php同样位于src目录,已使用正确的use和require语句,SMTP属性配置无误,附上emailer类代码:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require "PHPMailer/Exception.php";
require "PHPMailer/PHPMailer.php";
require "PHPMailer/SMTP.php";

require 'config.php';


function send_email($toAddress, $subject, $body) {

    $phpmailer = new PHPMailer(TRUE);
    $phpmailer->isSMTP();
    $phpmailer->Host = SMTP_Host;
    $phpmailer->SMTPAuth = SMTP_Auth;
    $phpmailer->Port = SMTP_Port;
    $phpmailer->Username = SMTP_Username;
    $phpmailer->Password = SMTP_Password;
    $phpmailer->SMTPSecure = SMTP_SecureMode;

    $phpmailer->setFrom(SMTP_SenderEmail, SMTP_SenderName);
    $phpmailer->addReplyTo(SMTP_SenderEmail, SMTP_SenderName);
    $phpmailer->addAddress($toAddress);

    $phpmailer->Subject = $subject;
    $phpmailer->isHTML = false;
    $phpmailer->Body = $body;

    if($phpmailer->send()){
        return 0;
    }else{
        $error = 'Message could not be sent. Mailer Error: ' . $phpmailer->ErrorInfo;
        error_log($error);

    }
}

解决方向

  • 检查PHPMailer文件完整性:该错误大概率是PHPMailer.php文件损坏或不完整,第2017行的PHPMailer应为类名引用,而非未定义常量。重新下载官方PHPMailer 6.8.0包,替换src/PHPMailer目录下的所有文件,确保文件无缺失或篡改。
  • 验证命名空间与类名:确认PHPMailer.php文件顶部的命名空间是namespace PHPMailer\PHPMailer;,且类名确实为PHPMailer,无拼写错误。
  • 修正require路径:尝试使用绝对路径加载文件,例如require __DIR__ . "/PHPMailer/PHPMailer.php";,避免相对路径在不同执行环境下的解析问题。
  • 清除PHP缓存:若启用了OPcache等缓存工具,重启PHP服务或清除OPcache缓存,确保最新文件内容被加载。
  • 排查命名冲突:确认项目中无其他自定义PHPMailer类或同名常量,避免命名冲突导致解析错误。

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 14:07:24