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

扩展PHPMailer类并自定义异常处理,处理邮件发送失败报错

解决PHPMailer特定发送错误的自定义异常处理

要针对"Service Closing transmission error."错误覆盖默认异常处理,可通过重写子类的send方法,捕获父类抛出的异常并做针对性判断处理,以下是修改后的完整代码:

<?php

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

require 'sendmail/vendor/autoload.php';

class MyPHPMailer extends PHPMailer{

    public function __construct($exceptions, $body = ''){
        parent::__construct($exceptions);

        $this->setFrom('your-yahoo-account@yahoo.com', 'Mahi');
        
        // 修正Yahoo SMTP配置,分开设置更规范
        $this->isSMTP();
        $this->Host = 'smtp.mail.yahoo.com';
        $this->Port = 587;
        $this->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $this->SMTPAuth = true;
        // Yahoo需使用应用授权码,而非邮箱登录密码
        $this->Username = 'your-yahoo-account@yahoo.com';
        $this->Password = 'your-yahoo-app-password';

        $this->msgHTML($body);
        $this->SMTPDebug = SMTP::DEBUG_SERVER;
    }

    public function send(){
        $this->Subject = '[Yay for me!] ' . $this->Subject;
        try {
            $r = parent::send();
            echo 'I sent a message with subject ' . $this->Subject;
            return $r;
        } catch (Exception $e) {
            // 检测是否为目标错误
            if (str_contains($e->getMessage(), 'Service Closing transmission error.')) {
                // 自定义处理逻辑,比如记录日志、发送告警等
                echo '自定义处理:SMTP服务意外关闭,执行特定操作';
                // 若需上层捕获异常,可取消注释重新抛出
                // throw new Exception('自定义提示:邮件发送时SMTP连接异常关闭', 0, $e);
                return false;
            }
            // 其他错误继续向上抛出
            throw $e;
        }
    }
}

try {
    $mail = new MyPHPMailer(true, '<strong>This is the message body</strong>');
    $mail->addAddress('recipient@yahoo.com', 'John');
    $mail->Subject = 'Here is the subject';
    $mail->addAttachment(__FILE__, 'myPHPMailer.php');
    $mail->send();
} catch (Exception $e) {
    echo 'Caught a ' . get_class($e) . ': ' . $e->getMessage();
}

关键修改说明:

  1. 在子类send方法中包裹父类调用,捕获异常后精准匹配目标错误信息
  2. 针对指定错误执行自定义逻辑,可选择返回失败状态或重新抛出自定义异常
  3. 修正Yahoo SMTP配置,补充必填的SMTPAuth、账号授权码信息(Yahoo禁用直接使用登录密码)
  4. 统一类名大小写,符合PHP命名规范

注意事项:

  • Yahoo邮箱需提前开启POP/IMAP服务,并生成应用授权码作为Password值
  • 若需保留原有异常传递链,可在自定义处理后重新抛出异常,确保上层代码能捕获到错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 16:54:28