Get mail php imap

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Manage mailboxes, filter/get/delete emails in PHP (supports IMAP/POP3/NNTP)

License

barbushin/php-imap

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Prevent TypeError while constructing ConnectionException.

Git stats

Files

Failed to load latest commit information.

README.md

Initially released in December 2012, the PHP IMAP Mailbox is a powerful and open source library to connect to a mailbox by POP3, IMAP and NNTP using the PHP IMAP extension. This library allows you to fetch emails from your email server. Extend the functionality or create powerful web applications to handle your incoming emails.

  • Connect to mailbox by POP3/IMAP/NNTP, using PHP IMAP extension
  • Get emails with attachments and inline images
  • Get emails filtered or sorted by custom criteria
  • Mark emails as seen/unseen
  • Delete emails
  • Manage mailbox folders
  • PHP fileinfo extension must be present; so make sure this line is active in your php.ini: extension=php_fileinfo.dll
  • PHP iconv extension must be present; so make sure this line is active in your php.ini: extension=php_iconv.dll
  • PHP imap extension must be present; so make sure this line is active in your php.ini: extension=php_imap.dll
  • PHP mbstring extension must be present; so make sure this line is active in your php.ini: extension=php_mbstring.dll
  • PHP json extension must be present; so make sure this line is active in your php.ini: extension=json.dll
$ composer require php-imap/php-imap 

Install the latest available and stable source code from master , which is may not released / tagged yet:

$ composer require php-imap/php-imap:dev-master 

Before you can run the any tests you may need to run composer install to install all (development) dependencies.

Читайте также:  Php вывести целое число

You can run all available tests by running the following command (inside of the installed php-imap directory): composer run tests

You can run all PHPUnit tests by running the following command (inside of the installed php-imap directory): php vendor/bin/phpunit —testdox

Integration with frameworks

Below, you’ll find an example code how you can use this library. For further information and other examples, you may take a look at the wiki.

By default, this library uses random filenames for attachments as identical file names from other emails would overwrite other attachments. If you want to keep the original file name, you can set the attachment filename mode to true , but then you also need to ensure, that those files don’t get overwritten by other emails for example.

// Create PhpImap\Mailbox instance for all further actions $mailbox = new PhpImap\Mailbox( 'INBOX', // IMAP server and mailbox folder 'some@gmail.com', // Username for the before configured mailbox '*********', // Password for the before configured username __DIR__, // Directory, where attachments will be saved (optional) 'UTF-8', // Server encoding (optional) true, // Trim leading/ending whitespaces of IMAP path (optional) false // Attachment filename mode (optional; false = random filename; true = original filename) ); // set some connection arguments (if appropriate) $mailbox->setConnectionArgs( CL_EXPUNGE // expunge deleted mails upon mailbox close | OP_SECURE // don't do non-secure authentication ); try < // Get all emails (messages) // PHP.net imap_search criteria: http://php.net/manual/en/function.imap-search.php $mailsIds = $mailbox->searchMailbox('ALL'); > catch(PhpImap\Exceptions\ConnectionException $ex) < echo "IMAP connection failed: " . implode(",", $ex->getErrors('all')); die(); > // If $mailsIds is empty, no emails could be found if(!$mailsIds) < die('Mailbox is empty'); > // Get the first message // If '__DIR__' was defined in the first line, it will automatically // save all attachments to the specified directory $mail = $mailbox->getMail($mailsIds[0]); // Show, if $mail has one or more attachments echo "\nMail has attachments? "; if($mail->hasAttachments()) < echo "Yes\n"; > else < echo "No\n"; > // Print all information of $mail print_r($mail); // Print all attachements of $mail echo "\n\nAttachments:\n"; print_r($mail->getAttachments());

Method imap() allows to call any PHP IMAP function in a context of the instance. Example:

// Call imap_check() - see http://php.net/manual/function.imap-check.php $info = $mailbox->imap('check'); // Show current time for the mailbox $currentServerTime = isset($info->Date) && $info->Date ? date('Y-m-d H:i:s', strtotime($info->Date)) : 'Unknown'; echo $currentServerTime;

Some request require much time and resources:

// If you don't need to grab attachments you can significantly increase performance of your application $mailbox->setAttachmentsIgnore(true); // get the list of folders/mailboxes $folders = $mailbox->getMailboxes('*'); // loop through mailboxs foreach($folders as $folder) < // switch to particular mailbox $mailbox->switchMailbox($folder['fullpath']); // search in particular mailbox $mails_ids[$folder['fullpath']] = $mailbox->searchMailbox('SINCE "1 Jan 2018" BEFORE "28 Jan 2018"'); > print_r($mails_ids);

Prior to 3.1, Mailbox used a «magic» method ( Mailbox::imap() ), with the class Imap now performing it’s purpose to call many imap_* functions with automated string encoding/decoding of arguments and return values:

public function checkMailbox() < return $this->imap('check'); >
public function checkMailbox(): object < return Imap::check($this->getImapStream()); >

About

Manage mailboxes, filter/get/delete emails in PHP (supports IMAP/POP3/NNTP)

Читайте также:  Java группы примитивных типов

Источник

Чтение почты через IMAP в PHP

В PHP без проблем можно работать с почтой через IMAP, для этого есть все необходимые функции, подробнее на php.net.

Получение писем

$imap = imap_open(«адрес», «e-mail», «пароль») – создает подключение к почтовому ящику. Далее, функция imap_search($imap, ‘ALL’) получает массив c индикаторами писем.

ALL Все сообщения
UNSEEN Непрочитанные сообщения
SEEN Прочтенные сообщения (установлен флаг seen)
NEW Новые сообщения (впервые появилось в ящике в ходе текущей сессии)
OLD Старые сообщения
ANSWERED Сообщения с флагом answered (отвеченный)
UNANSWERED Неотвеченные сообщения
DELETED Удаленные сообщения
UNDELETED Не удаленные сообщения
FLAGGED Сообщения с установленным флагом flagged (важное)
RECENT Сообщения с флагом recent (недавнее сообщение)
UNFLAGGED Сообщения без установленных флагов
ON «date» Сообщения с датой, равной « date »
BEFORE «date» Сообщения с датой, до « date »
SINCE «date» Сообщения с датой, после « date »
FROM «string» Сообщения в поле From: которых присутствует «string »
TO «string» Сообщения в поле To: которых присутствует «string »
SUBJECT «string» Сообщения, у которых присутствует «string » в поле Subject
BODY «string» Сообщения содержащие «string » в теле
TEXT «string» Сообщения с текстом «string »
KEYWORD «string» Сообщения с ключевым словом «string»
UNKEYWORD «string» Сообщения, не имеющие ключевого слова «string »

Далее массив обрабатывается в цикле, в примере происходит обход по всем письмам.

$imap = imap_open("INBOX", "mail@test.ru", "Пароль"); $mails_id = imap_search($imap, 'ALL'); foreach ($mails_id as $num) < // Заголовок письма $header = imap_header($imap, $num); var_dump($header); // Тело письма $body = imap_body($imap, $num); var_dump($body); >imap_close($imap);

$header = imap_header($imap, $num) – получает заголовки письма в виде объекта. Для удобства можно преобразовать в массив:

$header = imap_header($imap, $num); $header = json_decode(json_encode($header), true); print_r($header);
Array( [date] => Mon, 16 Sep 2019 16:03:56 +0300 [Date] => Mon, 16 Sep 2019 16:03:56 +0300 [subject] => =?UTF-8?B?SGVsbyBXb3JsZA==?= [Subject] => =?UTF-8?B?SGVsbyBXb3JsZA==?= [message_id] => [toaddress] => mail@snipp.ru [to] => Array( [0] => Array( [mailbox] => mail [host] => snipp.ru ) ) [fromaddress] => =?UTF-8?B?MTIzNDU2QHNpdGUucnU=?= [from] => Array( [0] => Array( [personal] => =?UTF-8?B?MTIzNDU2QHNpdGUucnU=?= [mailbox] => 123456 [host] => site.ru ) ) [ccaddress] => [cc] => [reply_toaddress] => [reply_to] => [senderaddress] => [sender] => [Recent] => [Unseen] => [Flagged] => [Answered] => [Deleted] => [Draft] => [Msgno] => 1 [MailDate] => 16-Sep-2019 16:03:59 +0300 [Size] => 38895 [udate] => 1568639039 )

Как видно в примере, тема письма и другие данные закодированы в base64 ( ?UTF-8?B?SGVsbyBXb3JsZA==?= ), декодировать их можно с помощью функции mb_decode_mimeheader() .

$header = imap_header($imap, $num); $header = json_decode(json_encode($header), true); echo mb_decode_mimeheader($header['subject']); 

$body = imap_body($imap, $num) – тело письма, обычный текст.

Читайте также:  Тег А

Может быть закодировано в quoted-printable (= D0=94=D0=BE=D0=B1=D1=80=D1=8B=D0=B9 ), раскодировать можно функцией quoted_printable_decode() .

$body = imap_body($imap, $num); $body = quoted_printable_decode($body); echo $body;

Установка флагов

imap_setflag_full ($imap, $num, $flag) – установит письму флаг, возможны значения:

seen Сообщение прочитано
answered На сообщение отправлен ответ
flagged Сообщение отмечено как «важное»
deleted Сообщение отмечено как удалённое
draft Сообщение отмечено как черновик
recent Недавнее сообщение

Можно установить сразу несколько флагов, разделяя их пробелами.

В примере, письмам, у которых в теме письма есть слово «заявка» устанавливается флаг «важное».

$imap = imap_open("INBOX", "mail@test.ru", "Пароль"); $mails_id = imap_search($imap, 'ALL'); foreach ($mails_id as $num) < // Заголовок письма $header = imap_header($imap, $num); $header = json_decode(json_encode($header), true); $subject = mb_decode_mimeheader($header['subject']); if (mb_strpos($subject, 'заявка') !== false) < imap_setflag_full($imap, $num, '\\flagged'); >> imap_close($imap);

Удаление писем

В цикле, письмо помечается функцией imap_delete() , после этого вызывается функция imap_expunge() , которая выполняет удаление всех помеченных писем.

$imap = imap_open("INBOX", "mail@site.ru", "Пароль"); $mails_id = imap_search($imap, 'ALL'); foreach ($mails_id as $num) < $header = imap_header($imap, $num); $body = imap_body($imap, $num); // Помечаем письмо как удаленное imap_delete($imap, $num); >// Удаление помеченных писем imap_expunge($imap); imap_close($imap);

Источник

Оцените статью