Skip to content

Instantly share code, notes, and snippets.

@Goerik
Created October 28, 2016 07:00
Show Gist options
  • Save Goerik/c5a18a1fd436f1c30c491b039d4c6188 to your computer and use it in GitHub Desktop.
Save Goerik/c5a18a1fd436f1c30c491b039d4c6188 to your computer and use it in GitHub Desktop.
<?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