Created
October 28, 2016 07:00
-
-
Save Goerik/c5a18a1fd436f1c30c491b039d4c6188 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* "require": { | |
* "php": ">=5.4", | |
* "php-imap/php-imap": "~2.0" | |
* }, | |
* | |
* sudo apt-get install php-imap | |
* | |
*/ | |
use PhpImap\IncomingMail; | |
class IncomingMailer | |
{ | |
private $mailbox; | |
public function __construct() | |
{ | |
$username = 'email@gmail.com'; | |
$password = '$password'; | |
$this->mailbox = new PhpImap\Mailbox('{imap.gmail.com:993/imap/ssl}INBOX', $username, $password, __DIR__); | |
} | |
/** | |
* Возвращает поисковый критерий | |
* @param $email | |
* @return string | |
*/ | |
public function getCriteria($email) | |
{ | |
return 'UNSEEN from "' . $email . '"'; | |
} | |
/** | |
* Получает список непрочитанных писем с указанного email | |
* @param $email | |
* @return array | |
*/ | |
public function getUnreadMessagesFrom($email) | |
{ | |
$messages = []; | |
$mailsIds = $this->mailbox->searchMailbox($this->getCriteria($email)); | |
foreach ($mailsIds as $mailsId) | |
{ | |
$messages[] = $this->mailbox->getMail($mailsId, false); | |
} | |
return array_reverse($messages); | |
} | |
/** | |
* Возвращает последнее непрочитанное сообщение от пользователя с $email | |
* @param $email | |
* @return null|IncomingMail | |
*/ | |
public function getLastUnreadMessage($email) | |
{ | |
$mailsIds = $this->mailbox->searchMailbox($this->getCriteria($email)); | |
$msgId = end($mailsIds); | |
if ($msgId !== false) | |
{ | |
return $this->mailbox->getMail($msgId, false); | |
} | |
return null; | |
} | |
/** | |
* Помечает сообщения прочитанными, начиная с переданного сообщения | |
* @param IncomingMail $message | |
*/ | |
public function markAsReadStatingFrom(IncomingMail $message) | |
{ | |
$email = $message->fromAddress; | |
$unreadMessages = $this->getUnreadMessagesFrom($email); | |
$needMark = false; | |
foreach ($unreadMessages as $unreadMessage) | |
{ | |
if ($unreadMessage->messageId === $message->messageId) | |
{ | |
$needMark = true; | |
} | |
if ($needMark) | |
{ | |
$this->mailbox->markMailAsRead($unreadMessage->id); | |
} | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment