时间:2021-07-01 10:21:17 帮助过:16人阅读
最近在业务场景里有接收解析用户主动发送的邮件,使用php-imap实现了这一需求,记录一下。
读取邮件的协议有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')); } }
推荐学习:《PHP视频教程》
以上就是详解使用php-imap查询操作邮件收件箱的详细内容,更多请关注gxlcms其它相关文章!