首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP Socket 實作 POP3 郵件類別(第二部分)

     編輯:PHP 相關知識

POP3 協定核心指令封裝:登出、狀態檢查、郵件統計與 Session ID 取得

承接第一部分(連線、認證),本文繼續實作 POP3 類別的核心功能方法,包含登出、連線狀態檢查、郵件總數/大小統計、單一郵件 Session ID 取得。

方法實作細節

1. 登出 popLogout()

function popLogout() {
    if (!$this->getIsConnect() && $this->bolIsLogin) return false;
    $this->sendCommand("QUIT");
    $this->getLineResponse();
    return $this->getRestIsSucceed();
}

發送 QUIT 指令結束會話,伺服器回應 +OK 表示成功。

2. 連線狀態檢查 getIsOnline()

function getIsOnline() {
    if (!$this->getIsConnect() && $this->bolIsLogin) return false;
    $this->sendCommand("NOOP");
    $this->getLineResponse();
    return $this->getRestIsSucceed();
}

NOOP(No Operation)用於保持連線活躍或檢查伺服器回應。

3. 取得郵件統計 getMailSum()

function getMailSum($intReturnType = 2) {
    if (!$this->getIsConnect() && $this->bolIsLogin) return false;
    $this->sendCommand("STAT");
    $strLineResponse = $this->getLineResponse();
    if (!$this->getRestIsSucceed()) return false;

    if ($intReturnType == 1) return $this->strResponse; // 原始回應字串

    $arrResponse = explode(" ", $this->strResponse);
    if (!is_array($arrResponse) || count($arrResponse) <= 0) {
        $this->setMessage('STAT command response message is error', 2006);
        return false;
    }
    // 回應格式:+OK 訊息數 總位元組數
    return array($arrResponse[1], $arrResponse[2]);
}

STAT 回應範例:+OK 10 123456,解析出訊息數與總大小。

4. 取得指定郵件 Session ID getMailSessId()

function getMailSessId($intMailId, $intReturnType = 2) {
    if (!$this->getIsConnect() && $this->bolIsLogin) return false;
    $this->sendCommand("UIDL $intMailId");
    $strLineResponse = $this->getLineResponse();
    if (!$this->getRestIsSucceed()) return false;

    if ($intReturnType == 1) return $this->strResponse;

    $arrResponse = explode(" ", $this->strResponse);
    if (!is_array($arrResponse) || count($arrResponse) < 2) {
        $this->setMessage('UIDL command response error', 2007);
        return false;
    }
    // 回應格式:+OK 郵件編號 UID
    return $arrResponse[2];
}

UIDL 回傳郵件唯一識別碼,支援跨會話追蹤郵件。

輔助方法說明

  • sendCommand($cmd):發送指令並加上 \r\n。
  • getLineResponse():讀取單行回應。
  • getRestIsSucceed():判斷回應是否以 +OK 開頭。
  • setMessage($msg, $code):記錄錯誤訊息與代碼。

使用情境

此類別可整合於郵件客戶端、自動化郵件處理系統、郵件備份工具等。注意 POP3 為明文傳輸,生產環境建議使用 POP3S (port 995) 或 STARTTLS 加密連線。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved