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

Codeigniter 3调用CI_Email::get_emails()报错:方法未定义

问题原因

CodeIgniter 3 自带的 CI_Email 类仅支持发送邮件,根本不存在 get_emails() 方法,这就是你调用该方法时触发错误的核心原因。

解决方案:使用PHPMailer实现POP3邮件读取

CodeIgniter原生不支持收邮件,推荐使用PHPMailer(成熟的邮件处理库)来实现POP3收件箱读取功能,步骤如下:

1. 准备PHPMailer

下载兼容PHP 5.6+的PHPMailer版本(适配CI3的PHP环境),将解压后的PHPMailer目录放入application/libraries下。

2. 替换控制器代码

将原有的read_emails()函数替换为以下代码:

public function read_emails() {
    // 加载数据库库
    $this->load->database();

    // 引入PHPMailer相关文件
    require_once APPPATH . 'libraries/PHPMailer/PHPMailer.php';
    require_once APPPATH . 'libraries/PHPMailer/POP3.php';

    $pop3 = new PHPMailer\PHPMailer\POP3();
    try {
        // 连接Gmail POP3服务器
        $pop3->connect(
            'pop.gmail.com',
            995,
            '你的邮箱地址',
            '你的Gmail应用密码(开启两步验证后生成)',
            30,
            true
        );

        // 获取收件箱邮件总数,限制最多读取20封避免超时
        $emailCount = $pop3->numMessages();
        $maxEmails = min($emailCount, 20);

        for ($i = 1; $i <= $maxEmails; $i++) {
            // 获取原始邮件内容并解析
            $rawEmail = $pop3->getMail($i);
            $mailParser = new PHPMailer\PHPMailer\PHPMailer();
            $mailParser->parseAddresses = true;
            
            if (!$mailParser->parse($rawEmail)) {
                continue; // 解析失败则跳过该邮件
            }

            // 校验邮件是否在24小时内收到
            $receivedTime = strtotime($mailParser->Date);
            if (time() - $receivedTime > 86400) {
                continue;
            }

            // 提取发件人邮箱地址
            $senderEmail = !empty($mailParser->from) ? $mailParser->from[0][0] : '';
            if (empty($senderEmail)) {
                continue;
            }

            // 检查数据库中是否已存在该邮箱
            $this->db->where('email', $senderEmail);
            $query = $this->db->get('contacts');
            
            if ($query->num_rows() == 0) {
                // 插入数据库
                $data = array(
                    'email' => $senderEmail,
                    'subject' => $mailParser->Subject,
                    'message' => $mailParser->body // 如需HTML内容可替换为$mailParser->HTMLBody
                );
                $this->db->insert('contacts', $data);
            }
        }

        // 关闭POP3连接
        $pop3->close();
    } catch (Exception $e) {
        // 记录错误日志
        log_message('error', 'POP3操作失败: ' . $e->getMessage());
    }
}

关键注意事项

  • Gmail配置:需在Gmail设置中开启POP3访问;若开启了两步验证,必须使用应用密码代替普通登录密码。
  • 服务器端口:确保服务器允许出站连接到995端口(POP3 SSL)。
  • 邮件数量限制:代码中限制最多读取20封邮件,可根据需求调整,避免一次性读取大量邮件导致超时。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 19:50:18