Determine the implementation method
There are two protocols for reading emails:POP3
andIMAP
, the difference is:The POP3
protocol allows email clients to download emails on the server, but operations on the client will not be fed back to the server.IMAP
Provides two-way communication between webmail and email clients. Operations on the client will be fed back to the server. For operations on emails, the emails on the server will also take corresponding actions.
The requirement requires that after processing the user's email, the email should be marked as processed, so theIMAP
protocol is selected.
Installation dependencies
Both local and server php need to install theimap
extension. Add the php-imap (https://github.com/barbushin/php-imap) extension to the project'scomposer.json
as follows:
"require": { "php-imap/php-imap": "^3.1", },
Configure related services
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 ); }
Get a list of all unread messages
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]; }
Mark certain messages as read
/** * @param array $mail_ids * @return mixed */ public function markRead($mail_ids) { return $this->mailbox->markMailsAsRead($mail_ids); }
Search for messages with specified topics and mark them as read
$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')); } }