搜尋
首頁後端開發php教程詳解使用php-imap查詢操作郵件收件匣

這篇文章帶大家介紹使用php-imap查詢操作郵件收件匣。有一定的參考價值,有需要的朋友可以參考一下,希望對大家有幫助。

最近在業務場景裡有接收解析使用者主動發送的郵件,使用php-imap實現了這一需求,記錄一下。

確定實作方式

讀取郵件的協定有POP3IMAP兩種,區別: POP3協定允許電子郵件用戶端下載伺服器上的郵件,但是在客戶端的操作,不會回饋到伺服器。 IMAP提供webmail與電子郵件用戶端之間的雙向通信,客戶端的操作都會回饋到伺服器上,對郵件進行的操作,伺服器上的郵件也會做相應的動作。

需求要求處理完使用者的郵件以後,將郵件標記為已處理,因此選用IMAP協定。

安裝依賴

本機、伺服器php皆需要安裝imap擴充功能。在專案的composer.json中加入php-imap(https://github.com/barbushin/php-imap)擴充功能如下:

"require": {
  "php-imap/php-imap": "^3.1",
},

配置相關服務

namespace app\library\service\mail;

use PhpImap\Exceptions\ConnectionException;
use PhpImap\Mailbox;

/**
 * 收邮件服务邮件API接口
 * Class PlayService
 * @package app\library\service
 */
class ImapService
{
    public $path = '{imap.263.net:993/imap/ssl}INBOX';   // IMAP server and mailbox folder
    public $login = 'user@263.cn';         // Username for the before configured mailbox
    public $password = 'pwd';                   // Password for the before configured username
    public $dir = null;        // Directory, where attachments will be saved (optional)
    public $encoding = 'UTF-8';   // Server encoding (optional)

    public $mailbox;

    public function __construct()
    {
        $this->mailbox = new Mailbox(
            $this->path,
            $this->login,
            $this->password,
            $this->dir,
            $this->encoding
        );
    }

取得所有未讀郵件清單

public function unSeenList()
{
    try {
        $mail_ids = $this->mailbox->searchMailbox('UNSEEN');
    } catch (ConnectionException $ex) {
        die('IMAP connection failed: ' . $ex->getMessage());
    } catch (\Exception $ex) {
        die('An error occured: ' . $ex->getMessage());
    }

    // If $mailsIds is empty, no emails could be found
    if (!$mail_ids) {
        die('Mailbox is empty');
    }

    try {
        $info = $this->mailbox->getMailsInfo($mail_ids);
    } catch (ConnectionException $ex) {
        echo "IMAP connection failed: " . $ex;
        die();
    }
    return ['ids' => $mail_ids, 'list' => $info];
}

將某些郵件標記為已讀

/**
 * @param array $mail_ids
 * @return mixed
 */
public function markRead($mail_ids)
{
    return $this->mailbox->markMailsAsRead($mail_ids);
}

搜尋指定主題的郵件並標記為已讀

$imap = new ImapService();
$condition = 'UNSEEN  SUBJECT "' . $title . '" SINCE "' . date('Y-m-d', strtotime('-1 days')) . '" FROM ' . $mail;
$data['mail'] = $imap->mailbox->searchMailbox($condition);
if (!empty($data['mail'])) {
    $data['info'] = $imap->mailbox->getMailsInfo($data['mail']);
    if ($params['mark'] == 1) {
        $data['mark'] = $imap->markRead(array_column($data['info'], 'uid'));
    }
}

推薦學習:《PHP影片教學

以上是詳解使用php-imap查詢操作郵件收件匣的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:segmentfault。如有侵權,請聯絡admin@php.cn刪除
優化PHP代碼:減少內存使用和執行時間優化PHP代碼:減少內存使用和執行時間May 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP電子郵件:分步發送指南PHP電子郵件:分步發送指南May 09, 2025 am 12:14 AM

phpisusedforsendendemailsduetoitsignegrationwithservermailservicesand andexternalsmtpproviders,自動化intifications andMarketingCampaigns.1)設置設置yourphpenvenvironnvironnvironmentwithaweberswithawebserverserververandphp,確保themailfunctionisenabled.2)useabasicscruct

如何通過PHP發送電子郵件:示例和代碼如何通過PHP發送電子郵件:示例和代碼May 09, 2025 am 12:13 AM

發送電子郵件的最佳方法是使用PHPMailer庫。 1)使用mail()函數簡單但不可靠,可能導致郵件進入垃圾郵件或無法送達。 2)PHPMailer提供更好的控制和可靠性,支持HTML郵件、附件和SMTP認證。 3)確保正確配置SMTP設置並使用加密(如STARTTLS或SSL/TLS)以增強安全性。 4)對於大量郵件,考慮使用郵件隊列系統來優化性能。

高級PHP電子郵件:自定義標題和功能高級PHP電子郵件:自定義標題和功能May 09, 2025 am 12:13 AM

CustomHeadersheadersandAdvancedFeaturesInphpeMailenHanceFunctionalityAndreliability.1)CustomHeadersheadersheadersaddmetadatatatatataatafortrackingandCategorization.2)htmlemailsallowformattingandttinganditive.3)attachmentscanmentscanmentscanbesmentscanbestmentscanbesentscanbesentingslibrarieslibrarieslibrariesliblarikelikephpmailer.4)smtppapapairatienticationaltication enterticationallimpr

使用PHP和SMTP發送電子郵件的指南使用PHP和SMTP發送電子郵件的指南May 09, 2025 am 12:06 AM

使用PHP和SMTP發送郵件可以通過PHPMailer庫實現。 1)安裝並配置PHPMailer,2)設置SMTP服務器細節,3)定義郵件內容,4)發送郵件並處理錯誤。使用此方法可以確保郵件的可靠性和安全性。

使用PHP發送電子郵件的最佳方法是什麼?使用PHP發送電子郵件的最佳方法是什麼?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

PHP中依賴注入的最佳實踐PHP中依賴注入的最佳實踐May 08, 2025 am 12:21 AM

使用依賴注入(DI)的原因是它促進了代碼的松耦合、可測試性和可維護性。 1)使用構造函數注入依賴,2)避免使用服務定位器,3)利用依賴注入容器管理依賴,4)通過注入依賴提高測試性,5)避免過度注入依賴,6)考慮DI對性能的影響。

PHP性能調整技巧和技巧PHP性能調整技巧和技巧May 08, 2025 am 12:20 AM

phpperformancetuningiscialbecapeitenhancesspeedandeffice,whatevitalforwebapplications.1)cachingwithapcureduccureducesdatabaseloadprovesrovessetimes.2)優化

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用