Skip to content

Instantly share code, notes, and snippets.

@DKepov
Created October 16, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DKepov/92a63f8550d70446f529 to your computer and use it in GitHub Desktop.
Save DKepov/92a63f8550d70446f529 to your computer and use it in GitHub Desktop.
receive letters for criteria
<?php
/**
 * Class Imap
 *
 * Инкапсуляция работы с почтой, по протоколу IMAP
 */
class Imap {

    private $imap_stream;

    /**
     * Конструктор imap соединения
     *
     * Создает руссурс соедиения с удаленным сервером,
     * Возвращает себя
     *
     * @param $host
     * @param $login
     * @param $password
     * @param $mailbox
     */
    public function __construct($host, $login, $password, $mailbox)
    {
        // Подключиться к ящику
        $this->imap_stream = imap_open('{'.$host.':993/imap/ssl}'.$mailbox, $login, $password);

        if ( ! $this->imap_stream)
        {
            return FALSE;
        }
    }

    /**
     * Автоматически закрывает соединение с удаленным сервером
     */
    public function __destruct()
    {
        if ($this->imap_stream)
        {
            // Отключиться от ящика (завершить сеанс)
            imap_close($this->imap_stream);
        }
    }

    /**
     * Критерии выборки писем с почты
     *
     * @param $criteria
     *
     * @return array|null Массив писем или пустота
     */
    public function fetch($criteria)
    {
        if ( ! $this->imap_stream OR !$criteria)
        {
            return NULL;
        }

        // Получаем список ID всех непрочитанных писем
        $all_unseen_email_ids = imap_search($this->imap_stream, 'UNSEEN', SE_UID);

        // Писем вообще нет
        if ( ! $all_unseen_email_ids)
        {
            return NULL;
        }

        // Получить список ID непрочитанных писем с нужного адреса
        $email_ids = imap_search($this->imap_stream, $criteria, SE_UID);

        // Помечаем остальные письма прочитанными
        if ( ! is_array($email_ids))
        {
            $email_ids = array();
        }

        $untargeted_email_ids = array_diff($all_unseen_email_ids, $email_ids);

        if ($untargeted_email_ids)
        {
            imap_setflag_full($this->imap_stream, implode(',', $untargeted_email_ids), "\\Seen", SE_UID);
        }

        // Нет писем по критерию
        if( ! $email_ids)
        {
            return NULL;
        }

        // Получаем сообщения и сразу отмечаем их, как прочитанные
        $messages = array();
        foreach ($email_ids as $email_id)
        {
            $struct = imap_fetchstructure($this->imap_stream, $email_id, FT_UID);
            $body = imap_fetchbody($this->imap_stream, $email_id, '1', FT_UID);

            if ($struct->encoding == 4)
            {
                $body = imap_qprint($body);
            }
            elseif($struct->encoding == 3)
            {
                $body = imap_base64($body);
            }

            $messages[] = $body;
        }

        // Есть что возвращать
        return $messages;
    }

}
@DKepov
Copy link
Author

DKepov commented Oct 16, 2015

/**
 * Class Imap
 *
 * Инкапсуляция работы с почтой, по протоколу IMAP
 */
class Imap {

    private $imap_stream;

    /**
     * Конструктор imap соединения
     *
     * Создает руссурс соедиения с удаленым сервером,
     * Возвращает себя
     *
     * @param $host
     * @param $login
     * @param $password
     * @param $mailbox
     */
    public function __construct($host, $login, $password, $mailbox)
    {
        // Подключиться к ящику
        $this->imap_stream = imap_open('{'.$host.':993/imap/ssl}'.$mailbox, $login, $password);

        if ( ! $this->imap_stream)
        {
            return FALSE;
        }
    }

    /**
     * Автоматически закрывает соединение с удаленым сервером
     */
    public function __destruct()
    {
        if ($this->imap_stream)
        {
            // Отключиться от ящика (завершить сеанс)
            imap_close($this->imap_stream);
        }
    }

    /**
     * Критерии выборки писем с почты
     *
     * @param $criteria
     *
     * @return array|null Массив писем или пустота
     */
    public function fetch($criteria)
    {
        if ( ! $this->imap_stream OR !$criteria)
        {
            return NULL;
        }

        // Получаем список ID всех непрочитанных писем
        $all_unseen_email_ids = imap_search($this->imap_stream, 'UNSEEN', SE_UID);

        // Писем вообще нет
        if ( ! $all_unseen_email_ids)
        {
            return NULL;
        }

        // Получить список ID непрочитанных писем с нужного адреса
        $email_ids = imap_search($this->imap_stream, $criteria, SE_UID);

        // Помечаем остальные письма прочитанными
        if ( ! is_array($email_ids))
        {
            $email_ids = array();
        }

        $untargeted_email_ids = array_diff($all_unseen_email_ids, $email_ids);

        if ($untargeted_email_ids)
        {
            imap_setflag_full($this->imap_stream, implode(',', $untargeted_email_ids), "\\Seen", SE_UID);
        }

        // Нет писем по критерию
        if( ! $email_ids)
        {
            return NULL;
        }

        // Получаем сообщения и сразу отмечаем их, как прочитанные
        $messages = array();
        foreach ($email_ids as $email_id)
        {
            $struct = imap_fetchstructure($this->imap_stream, $email_id, FT_UID);
            $body = imap_fetchbody($this->imap_stream, $email_id, '1', FT_UID);

            if ($struct->encoding == 4)
            {
                $body = imap_qprint($body);
            }
            elseif($struct->encoding == 3)
            {
                $body = imap_base64($body);
            }

            $messages[] = $body;
        }

        // Есть что возвращать
        return $messages;
    }

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment