確定實作方式
讀取郵件的協定有POP3
和IMAP
兩種,區別: 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')); } }