确定实现方式
读取邮件的协议有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", },
Salin selepas log masuk
配置相关服务
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 ); }
Salin selepas log masuk
获取所有未读邮件列表
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]; }
Salin selepas log masuk
将某些邮件标记为已读
/** * @param array $mail_ids * @return mixed */ public function markRead($mail_ids) { return $this->mailbox->markMailsAsRead($mail_ids); }
Salin selepas log masuk
搜索指定主题的邮件并标记为已读
$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')); } }
Salin selepas log masuk