最近在业务场景里有接管解析用户被动发送的邮件,应用 php-imap 实现了这一需要,记录一下。
确定实现形式
读取邮件的协定有 POP3
和IMAP
两种,区别:POP3
协定容许电子邮件客户端下载服务器上的邮件,然而在客户端的操作,不会反馈到服务器上。IMAP
提供 webmail 与电子邮件客户端之间的双向通信,客户端的操作都会反馈到服务器上,对邮件进行的操作,服务器上的邮件也会做相应的动作。
需要要求解决完用户的邮件当前,将邮件标记为已解决,因而选用 IMAP
协定。
装置依赖
本地、服务器 php 均须要装置 imap
扩大。在我的项目的 composer.json
中增加 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'));
}
}