PHPackages                             smartilabs/php-imap - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Mail &amp; Notifications](/categories/mail)
4. /
5. smartilabs/php-imap

ActiveLibrary[Mail &amp; Notifications](/categories/mail)

smartilabs/php-imap
===================

PHP IMAP client

2.2.3(5y ago)053MITPHPPHP &gt;=5.5.9

Since Aug 13Pushed 5y agoCompare

[ Source](https://github.com/smartilabs/php-imap)[ Packagist](https://packagist.org/packages/smartilabs/php-imap)[ Docs](https://github.com/webklex/php-imap)[ RSS](/packages/smartilabs-php-imap/feed)WikiDiscussions master Synced today

READMEChangelogDependencies (3)Versions (27)Used By (0)

IMAP Library for PHP
====================

[](#imap-library-for-php)

[![Latest Version on Packagist](https://camo.githubusercontent.com/51ede80ebd30e1a5d815f3276deb7f2b98991b7d6737c531057c52225f38cbe3/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f5765626b6c65782f7068702d696d61702e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/Webklex/php-imap)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](https://github.com/Webklex/php-imap/blob/master/LICENSE)[![Build Status](https://camo.githubusercontent.com/270486ad45ee82771e175db62b5b0e676a2f9703a8178dadb28682bc6ed23b0d/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f6275696c642f672f5765626b6c65782f7068702d696d61702f6d61737465723f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/Webklex/php-imap/code-structure)[![Total Downloads](https://camo.githubusercontent.com/095b04338c33d3732932ec5233258d879813091fe55721061687aaa33f8b28b0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f5765626b6c65782f7068702d696d61702e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/Webklex/php-imap)[![Hits](https://camo.githubusercontent.com/3d0c66224e82cc1267b034c33b902fcddccc1d90596082538461da2fccc0eaa8/68747470733a2f2f686974732e7765626b6c65782e636f6d2f7376672f7765626b6c65782f7068702d696d6170)](https://hits.webklex.com)

Description
-----------

[](#description)

PHP-IMAP is a wrapper for common IMAP communication without the need to have the php-imap module installed / enabled. The protocol is completely integrated and therefore supports IMAP IDLE operation and the "new" oAuth authentication process as well. You can enable the `php-imap` module in order to handle edge cases, improve message decoding quality and is required if you want to use legacy protocols such as pop3.

Wiki: [webklex/php-imap/wiki](https://github.com/Webklex/php-imap/wiki)

Laravel wrapper: [webklex/laravel-imap](https://github.com/Webklex/laravel-imap)

Table of Contents
-----------------

[](#table-of-contents)

- [Installation](#installation)
- [Configuration](#configuration)
- [Usage](#usage)
    - [Basic usage example](#basic-usage-example)
    - [Folder / Mailbox](#folder--mailbox)
    - [oAuth](#oauth)
    - [Idle](#idle)
    - [Search](#search-for-messages)
    - [Counting messages](#counting-messages)
    - [Result limiting](#result-limiting)
    - [Pagination](#pagination)
    - [View examples](#view-examples)
    - [Fetch a specific message](#fetch-a-specific-message)
    - [Message flags](#message-flags)
    - [Attachments](#attachments)
    - [Advanced fetching](#advanced-fetching)
    - [Events](#events)
    - [Masking](#masking)
    - [Specials](#specials)
- [Support](#support)
- [Documentation](#documentation)
    - [Client::class](#clientclass)
    - [Message::class](#messageclass)
    - [Folder::class](#folderclass)
    - [Query::class](#queryclass)
    - [Attachment::class](#attachmentclass)
    - [Mask::class](#maskclass)
        - [MessageMask::class](#messagemaskclass)
        - [AttachmentMask::class](#attachmentmaskclass)
    - [MessageCollection::class](#messagecollectionclass)
    - [AttachmentCollection::class](#attachmentcollectionclass)
    - [FolderCollection::class](#foldercollectionclass)
    - [FlagCollection::class](#flagcollectionclass)
- [Known issues](#known-issues)
- [Milestones &amp; upcoming features](#milestones--upcoming-features)
- [Security](#security)
- [Credits](#credits)
- [License](#license)

Installation
------------

[](#installation)

1.) Install decoding modules:

```
sudo apt-get install php*-mbstring php*-mcrypt && sudo apache2ctl graceful
```

1.1.) (optional) Install php-imap module if you are having encoding problems:

```
sudo apt-get install php*-imap && sudo apache2ctl graceful
```

You might also want to check `phpinfo()` if the extensions are enabled.

2.) Now install the PHP-IMAP package by running the following command:

```
composer require webklex/php-imap
```

3.) Create your own custom config file like [config/imap.php](src/config/imap.php):

Configuration
-------------

[](#configuration)

Supported protocols:

- `imap` — Use IMAP \[default\]
- `legacy-imap` — Use the php imap module instead
- `pop3` — Use POP3
- `nntp` — Use NNTP

The following encryption methods are supported:

- `false` — Disable encryption
- `ssl` — Use SSL
- `tls` — Use TLS
- `starttls` — Use STARTTLS (alias TLS) (legacy only)
- `notls` — Use NoTLS (legacy only)

Detailed [config/imap.php](src/config/imap.php) configuration:

- `default` — used default account. It will be used as default for any missing account parameters. If however the default account is missing a parameter the package default will be used. Set to `false` to disable this functionality.
- `accounts` — all available accounts
    - `default` — The account identifier (in this case `default` but could also be `fooBar` etc).
        - `host` — imap host
        - `port` — imap port
        - `encryption` — desired encryption method
        - `validate_cert` — decide weather you want to verify the certificate or not
        - `username` — imap account username
        - `password` — imap account password
        - `authentication` — imap authentication method. Use `oauth` to use oAuth for Google, etc.
- `date_format` — The default date format is used to convert any given Carbon::class object into a valid date string. (`d-M-Y`, `d-M-y`, `d M y`)
- `options` — additional fetch options
    - `delimiter` — you can use any supported char such as ".", "/", etc
    - `fetch` — `IMAP::FT_UID` (message marked as read by fetching the message body) or `IMAP::FT_PEEK` (fetch the message without setting the "seen" flag)
    - `fetch_body` — If set to `false` all messages will be fetched without the body and any potential attachments
    - `fetch_flags` — If set to `false` all messages will be fetched without any flags
    - `message_key` — Message key identifier option
    - `fetch_order` — Message fetch order
    - `common_folders` — Default folder locations and paths assumed if none is provided
    - `open` — special configuration for imap\_open()
        - `DISABLE_AUTHENTICATOR` — disable authentication properties.
    - `decoder` — Currently only the message and attachment decoder can be set
    - `events` — Default [event handling](#events) config
    - `masks` — Default [masking](#masking) config
        - `message` — Default message mask
        - `attachment` — Default attachment mask

Usage
-----

[](#usage)

#### Basic usage example

[](#basic-usage-example)

This is a basic example, which will echo out all Mails within all imap folders and will move every message into INBOX.read. Please be aware that this should not be tested in real life and is only meant to gives an impression on how things work.

```
use Webklex\PHPIMAP\ClientManager;
use Webklex\PHPIMAP\Client;

$cm = new ClientManager('path/to/config/imap.php');

// or use an array of options instead
$cm = new ClientManager($options = []);

/** @var \Webklex\PHPIMAP\Client $client */
$client = $cm->account('account_identifier');

// or create a new instance manually
$client = $cm->make([
    'host'          => 'somehost.com',
    'port'          => 993,
    'encryption'    => 'ssl',
    'validate_cert' => true,
    'username'      => 'username',
    'password'      => 'password',
    'protocol'      => 'imap'
]);

//Connect to the IMAP Server
$client->connect();

//Get all Mailboxes
/** @var \Webklex\PHPIMAP\Support\FolderCollection $folders */
$folders = $client->getFolders();

//Loop through every Mailbox
/** @var \Webklex\PHPIMAP\Folder $folder */
foreach($folders as $folder){

    //Get all Messages of the current Mailbox $folder
    /** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
    $messages = $folder->messages()->all()->get();

    /** @var \Webklex\PHPIMAP\Message $message */
    foreach($messages as $message){
        echo $message->getSubject().'';
        echo 'Attachments: '.$message->getAttachments()->count().'';
        echo $message->getHTMLBody();

        //Move the current Message to 'INBOX.read'
        if($message->move('INBOX.read') == true){
            echo 'Message has ben moved';
        }else{
            echo 'Message could not be moved';
        }
    }
}
```

#### Folder / Mailbox

[](#folder--mailbox)

List all available folders:

```
/** @var \Webklex\PHPIMAP\Client $client */

/** @var \Webklex\PHPIMAP\Support\FolderCollection $folders */
$folders = $client->getFolders();
```

Get a specific folder:

```
/** @var \Webklex\PHPIMAP\Client $client */

/** @var \Webklex\PHPIMAP\Folder $folder */
$folder = $client->getFolder('INBOX.name');
```

#### oAuth

[](#oauth)

Please take a look at [the wiki article](https://github.com/Webklex/php-imap/wiki/Google-Mail---Gmail) for gmail / google mail setup.

Basic oAuth example:

```
use Webklex\PHPIMAP\Clientmanager;

$cm = new Clientmanager();

/** @var \Webklex\PHPIMAP\Client $client */
$client = $cm->make([
    'host' => 'imap.gmail.com',
    'port' => 993,
    'encryption' => 'ssl',
    'validate_cert' => true,
    'username' => 'example@gmail.com',
    'password' => 'ACCESS-TOKEN',
    'authentication' => "oauth",
    'protocol' => 'imap'
]);

//Connect to the IMAP Server
$client->connect();
```

#### Idle

[](#idle)

Every time a new message is received, the server will notify the client and return the new message.

```
/** @var \Webklex\PHPIMAP\Folder $folder */
$folder->idle(function($message){
    echo $message->subject."\n";
});
```

#### Search for messages

[](#search-for-messages)

Search for specific emails:

```
/** @var \Webklex\PHPIMAP\Folder $folder */

//Get all messages
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->all()->get();

//Get all messages from example@domain.com
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->from('example@domain.com')->get();

//Get all messages since march 15 2018
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->since('15.03.2018')->get();

//Get all messages within the last 5 days
$messages = $folder->query()->since(\Carbon\Carbon::now()->subDays(5))->get();

//Get all messages containing "hello world"
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->text('hello world')->get();

//Get all unseen messages containing "hello world"
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->unseen()->text('hello world')->get();

//Extended custom search query for all messages containing "hello world"
//and have been received since march 15 2018
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->text('hello world')->since('15.03.2018')->get();
$messages = $folder->query()->Text('hello world')->Since('15.03.2018')->get();
$messages = $folder->query()->whereText('hello world')->whereSince('15.03.2018')->get();

// Build a custom search query
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()
->where([['TEXT', 'Hello world'], ['SINCE', \Carbon\Carbon::parse('15.03.2018')]])
->get();

//!EXPERIMENTAL!
//Get all messages NOT containing "hello world"
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->notText('hello world')->get();
$messages = $folder->query()->not_text('hello world')->get();
$messages = $folder->query()->not()->text('hello world')->get();

//Get all messages by custom search criteria
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->where(["CUSTOM_FOOBAR" => "fooBar"]])->get();
```

Available search aliases for a better code reading:

```
// Folder::search() is just an alias for Folder::query()
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->search()->text('hello world')->since('15.03.2018')->get();

// Folder::messages() is just an alias for Folder::query()
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->messages()->text('hello world')->since('15.03.2018')->get();
```

All available query / search methods can be found here: [Query::class](src/Query/WhereQuery.php)

Available search criteria:

- `ALL` — return all messages matching the rest of the criteria
- `ANSWERED` — match messages with the \\ANSWERED flag set
- `BCC` "string" — match messages with "string" in the Bcc: field
- `BEFORE` "date" — match messages with Date: before "date"
- `BODY` "string" — match messages with "string" in the body of the message
- `CC` "string" — match messages with "string" in the Cc: field
- `DELETED` — match deleted messages
- `FLAGGED` — match messages with the \\FLAGGED (sometimes referred to as Important or Urgent) flag set
- `FROM` "string" — match messages with "string" in the From: field
- `KEYWORD` "string" — match messages with "string" as a keyword
- `NEW` — match new messages
- `NOT` — not matching
- `OLD` — match old messages
- `ON` "date" — match messages with Date: matching "date"
- `RECENT` — match messages with the \\RECENT flag set
- `SEEN` — match messages that have been read (the \\SEEN flag is set)
- `SINCE` "date" — match messages with Date: after "date"
- `SUBJECT` "string" — match messages with "string" in the Subject:
- `TEXT` "string" — match messages with text "string"
- `TO` "string" — match messages with "string" in the To:
- `UNANSWERED` — match messages that have not been answered
- `UNDELETED` — match messages that are not deleted
- `UNFLAGGED` — match messages that are not flagged
- `UNKEYWORD` "string" — match messages that do not have the keyword "string"
- `UNSEEN` — match messages which have not been read yet

Further information:

-
-
-
-
-

#### Result limiting

[](#result-limiting)

Limiting the request emails:

```
/** @var \Webklex\PHPIMAP\Folder $folder */

//Get all messages for page 2 since march 15 2018 where each page contains 10 messages
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->since('15.03.2018')->limit(10, 2)->get();
```

#### Counting messages

[](#counting-messages)

Count all available messages matching the current search criteria:

```
/** @var \Webklex\PHPIMAP\Folder $folder */

//Count all messages
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$count = $folder->query()->all()->count();

//Count all messages since march 15 2018
$count = $folder->query()->since('15.03.2018')->count();
```

#### Pagination

[](#pagination)

Paginate a query:

```
/** @var \Webklex\PHPIMAP\Folder $folder */

/** @var \Illuminate\Pagination\LengthAwarePaginator $paginator */
$paginator = $folder->query()->since('15.03.2018')->paginate();
```

Paginate a message collection:

```
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */

/** @var \Illuminate\Pagination\LengthAwarePaginator $paginator */
$paginator = $messages->paginate();
```

View example for a paginated list:

```
/** @var \Webklex\PHPIMAP\Folder $folder */

/** @var \Illuminate\Pagination\LengthAwarePaginator $paginator */
$paginator = $folder->search()
->since(\Carbon\Carbon::now()->subDays(14))->get()
->paginate($perPage = 5, $page = null, $pageName = 'imap_blade_example');
```

```

        UID
        Subject
        From
        Attachments

        count() > 0): ?>

                getUid(); ?>
                getSubject(); ?>
                getFrom()[0]->mail; ?>
                getAttachments()->count() > 0 ? 'yes' : 'no'; ?>

                No messages found

links(); ?>
```

> You can also paginate a Folder-, Attachment- or FlagCollection instance.

#### View examples

[](#view-examples)

You can find a few blade examples under [/examples](examples).

#### Fetch a specific message

[](#fetch-a-specific-message)

Get a specific message by uid (Please note that the uid is not unique and can change):

```
/** @var \Webklex\PHPIMAP\Folder $folder */

/** @var \Webklex\PHPIMAP\Message $message */
$message = $folder->query()->getMessage($msgn = 1);
```

#### Message flags

[](#message-flags)

Flag or "unflag" a message:

```
/** @var \Webklex\PHPIMAP\Message $message */
$message->setFlag(['Seen', 'Spam']);
$message->unsetFlag('Spam');
```

Mark all messages as "read" while fetching:

```
/** @var \Webklex\PHPIMAP\Folder $oFolder */
/** @var \Webklex\PHPIMAP\Support\MessageCollection $aMessage */
$aMessage = $oFolder->query()->text('Hello world')->markAsRead()->get();
```

Don't mark all messages as "read" while fetching:

```
/** @var \Webklex\PHPIMAP\Folder $oFolder */
/** @var \Webklex\PHPIMAP\Support\MessageCollection $aMessage */
$aMessage = $oFolder->query()->text('Hello world')->leaveUnread()->get();
```

#### Attachments

[](#attachments)

Save message attachments:

```
/** @var \Webklex\PHPIMAP\Message $message */

/** @var \Webklex\PHPIMAP\Support\AttachmentCollection $attachments */
$attachments = $message->getAttachments();

$attachments->each(function ($attachment) {
    /** @var \Webklex\PHPIMAP\Attachment $attachment */
    $attachment->save("/some/path/");
});
```

#### Advanced fetching

[](#advanced-fetching)

Fetch messages without body fetching (decrease load):

```
/** @var \Webklex\PHPIMAP\Folder $folder */

/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->whereText('Hello world')->setFetchBody(false)->get();

/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->whereAll()->setFetchBody(false)->get();
```

Fetch messages without body, flag and attachment fetching (decrease load):

```
/** @var \Webklex\PHPIMAP\Folder $folder */

/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->whereText('Hello world')
->setFetchFlags(false)
->setFetchBody(false)
->get();

/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->whereAll()
->setFetchFlags(false)
->setFetchBody(false)
->get();
```

Change messages fetch order:

```
/** @var \Webklex\PHPIMAP\Folder $folder */

/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->whereText('Hello world')
->setFetchOrder('asc')
->get();

/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->whereAll()
->setFetchOrderAsc()
->get();

/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->whereAll()
->fetchOrderAsc()
->get();

/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->whereText('Hello world')
->setFetchOrder('desc')
->get();

/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->whereAll()
->setFetchOrderDesc()
->get();

/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->whereAll()
->fetchOrderDesc()
->get();
```

#### Events

[](#events)

The following events are available:

- `Webklex\PHPIMAP\Events\MessageNewEvent($message)` — can get triggered by `Folder::idle`
- `Webklex\PHPIMAP\Events\MessageDeletedEvent($message)` — triggered by `Message::delete`
- `Webklex\PHPIMAP\Events\MessageRestoredEvent($message)` — triggered by `Message::restore`
- `Webklex\PHPIMAP\Events\MessageMovedEvent($old_message, $new_message)` — triggered by `Message::move`
- `Webklex\PHPIMAP\Events\MessageCopiedEvent($old_message, $new_message)` — triggered by `Message::copy`
- `Webklex\PHPIMAP\Events\FlagNewEvent($flag)` — triggered by `Message::setFlag`
- `Webklex\PHPIMAP\Events\FlagDeletedEvent($flag)` — triggered by `Message::unsetFlag`
- `Webklex\PHPIMAP\Events\FolderNewEvent($folder)` — can get triggered by `Client::createFolder`
- `Webklex\PHPIMAP\Events\FolderDeletedEvent($folder)` — triggered by `Folder::delete`
- `Webklex\PHPIMAP\Events\FolderMovedEvent($old_folder, $new_folder)` — triggered by `Folder::move`

Create and register your own custom event:

```
class CustomMessageNewEvent extends Webklex\PHPIMAP\Events\MessageNewEvent {

    /**
     * Create a new event instance.
     * @var \Webklex\PHPIMAP\Message[] $messages
     * @return void
     */
    public function __construct($messages) {
        $this->message = $messages[0];
        echo "New message: ".$this->message->subject."\n";
    }
}

/** @var \Webklex\PHPIMAP\Client $client */
$client->setEvent("message", "new", CustomMessageNewEvent::class);
```

..or set it in your config file under `events.message.new`.

#### Masking

[](#masking)

PHP-IMAP already comes with two default masks [MessageMask::class](#messagemaskclass) and [AttachmentMask::class](#attachmentmaskclass).

The masked instance has to be called manually and is designed to add custom functionality.

You can call the default mask by calling the mask method without any arguments.

```
/** @var \Webklex\PHPIMAP\Message $message */
$mask = $message->mask();
```

There are several methods available to set the default mask:

```
/** @var \Webklex\PHPIMAP\Client $client */
/** @var \Webklex\PHPIMAP\Message $message */

$message_mask = \Webklex\PHPIMAP\Support\Masks\MessageMask::class;

$client->setDefaultMessageMask($message_mask);
$message->setMask($message_mask);
$mask = $message->mask($message_mask);
```

The last one wont set the mask but generate a masked instance using the provided mask.

You could also set the default masks inside your `config/imap.php` file under `masks`.

You can also apply a mask on [attachments](#attachmentclass):

```
/** @var \Webklex\PHPIMAP\Client $client */
/** @var \Webklex\PHPIMAP\Attachment $attachment */
$attachment_mask = \Webklex\PHPIMAP\Support\Masks\AttachmentMask::class;

$client->setDefaultAttachmentMask($attachment_mask);
$attachment->setMask($attachment_mask);
$mask = $attachment->mask($attachment_mask);
```

If you want to implement your own mask just extend [MessageMask::class](#messagemaskclass), [AttachmentMask::class](#attachmentmaskclass)or [Mask::class](#maskclass) and implement your desired logic:

```
/** @var \Webklex\PHPIMAP\Message $message */
class CustomMessageMask extends \Webklex\PHPIMAP\Support\Masks\MessageMask {

    /**
     * New custom method which can be called through a mask
     * @return string
     */
    public function token(){
        return implode('-', [$this->message_id, $this->uid, $this->message_no]);
    }
}

$mask = $message->mask(CustomMessageMask::class);

echo $mask->token().'@'.$mask->uid;
```

Additional examples can be found here:

- [Custom message mask](https://github.com/Webklex/php-imap/blob/master/examples/custom_message_mask.php)
- [Custom attachment mask](https://github.com/Webklex/php-imap/blob/master/examples/custom_attachment_mask.php)

#### Specials

[](#specials)

Find the folder containing a message:

```
/** @var \Webklex\PHPIMAP\Message $message */
$folder = $message->getFolder();
```

Support
-------

[](#support)

If you encounter any problems or if you find a bug, please don't hesitate to create a new [issue](https://github.com/Webklex/php-imap/issues). However please be aware that it might take some time to get an answer. Off topic, rude or abusive issues will be deleted without any notice.

If you need **immediate** or **commercial** support, feel free to send me a mail at .

##### A little notice

[](#a-little-notice)

If you write source code in your issue, please consider to format it correctly. This makes it so much nicer to read and people are more likely to comment and help :)

``` php

echo 'your php code...';

```

will turn into:

```
echo 'your php code...';
```

### Features &amp; pull requests

[](#features--pull-requests)

Everyone can contribute to this project. Every pull request will be considered but it can also happen to be declined. To prevent unnecessary work, please consider to create a [feature issue](https://github.com/Webklex/php-imap/issues/new?template=feature_request.md)first, if you're planning to do bigger changes. Of course you can also create a new [feature issue](https://github.com/Webklex/php-imap/issues/new?template=feature_request.md)if you're just wishing a feature ;)

Documentation
-------------

[](#documentation)

### [Client::class](src/Client.php)

[](#clientclass)

MethodArgumentsReturnDescriptionsetConfigarray $configselfSet the Client configuration. Take a look at `config/imap.php` for more inspiration.getConnectionresource $connectionresourceGet the current imap resourceisConnectedboolDetermine if connection was established.checkConnectionDetermine if connection was established and connect if not.connectConnect to server.reconnectTerminate and reconnect to server.disconnectDisconnect from server.getFolderstring $folder\_name, $delimiter = nullFolderGet a Folder instance by name or pathgetFoldersbool $hierarchical, string or null $parent\_folderFolderCollectionGet folders list. If hierarchical order is set to true, it will make a tree of folders, otherwise it will return flat array.openFolderstring or Folder $folder, integer $attemptsOpen a given folder.createFolderstring $namebooleanCreate a new folder.getQuotaarrayRetrieve the quota level settings, and usage statics per mailboxgetQuotaRootstring $quota\_rootarrayRetrieve the quota settings per userexpungeboolDelete all messages marked for deletionsetTimeoutstring or int $type, int $timeoutbooleanSet the timeout for certain imap operations: 1: Open, 2: Read, 3: Write, 4: ClosegetTimeoutstring or int $typeintCheck current mailboxsetDefaultMessageMaskstring $maskselfSet the default message mask classgetDefaultMessageMaskstringGet the current default message mask class namesetDefaultAttachmentMaskstring $maskselfSet the default attachment mask classgetDefaultAttachmentMaskstringGet the current default attachment mask class namegetFolderPathstringGet the current folder path### [Message::class](src/Message.php)

[](#messageclass)

MethodArgumentsReturnDescriptionparseBodyMessageParse the Message bodydeleteboolean $expungebooleanDelete the current Messagerestoreboolean $expungebooleanRestore a deleted Messagecopystring $mailboxbooleanCopy the current Messages to a mailboxmovestring $mailbox, boolean $expungebooleanMove the current Messages to a mailboxsetFlagstring or array $flagbooleanSet one or many flagsunsetFlagstring or array $flagbooleanUnset one or many flagshasTextBodyCheck if the Message has a text bodyhasHTMLBodyCheck if the Message has a html bodygetTextBodystringGet the Message text bodygetHTMLBodystringGet the Message html bodygetAttachmentsAttachmentCollectionGet all message attachmentshasAttachmentsbooleanChecks if there are any attachments presentgetClientClientGet the current Client instancegetUidstringGet the current UIDgetFetchOptionsstringGet the current fetch optiongetMsglistintegerGet the current message listgetHeaderInfoobjectGet the current header\_info objectgetHeaderstringGet the current raw headergetMessageIdstringGet the current message IDgetMessageNointegerGet the current message numbergetPriorityintegerGet the current message prioritygetSubjectstringGet the current subjectgetReferencesmixedGet any potentially present referencesgetDateCarbonGet the current date objectgetFromarrayGet the current from informationgetToarrayGet the current to informationgetCcarrayGet the current cc informationgetBccarrayGet the current bcc informationgetReplyToarrayGet the current reply to informationgetInReplyTostringGet the current In-Reply-TogetSenderarrayGet the current sender informationgetBodiesmixedGet the current bodiesgetRawBodymixedGet the current raw message bodygetFlagsFlagCollectionGet the current message flagsisbooleanDoes this message match another one?getStructureobjectThe raw message structuregetFolderFolderThe current foldermaskstring $mask = nullMaskGet a masked instancesetMaskstring $maskMessageSet the mask classgetMaskstringGet the current mask class name### [Folder::class](src/Folder.php)

[](#folderclass)

MethodArgumentsReturnDescriptionhasChildrenboolDetermine if folder has children.setChildrenarray $childrenselfSet children.deleteDelete the current MailboxsubscribeSubscribe to the current MailboxunsubscribeUnsubscribe from the current Mailboxidlecallable $callback(Message $new\_message)Idle the current foldermovestring $mailboxMove or Rename the current Mailboxrenamestring $mailboxMove or Rename the current MailboxgetStatusarrayReturns status information on the current mailboxexaminearrayReturns status information on the current mailboxappendMessagestring $message, string $options, string $internal\_dateboolAppend a string message to the current mailboxgetClientClientGet the current Client instancequerystring $charset = 'UTF-8'WhereQueryGet the current Client instancemessagesstring $charset = 'UTF-8'WhereQueryAlias for Folder::query()searchstring $charset = 'UTF-8'WhereQueryAlias for Folder::query()### [Query::class](src/Query/WhereQuery.php)

[](#queryclass)

MethodArgumentsReturnDescriptionwheremixed $criteria, $value = nullWhereQueryAdd new criteria to the current queryorWhereClosure $closureWhereQueryIf supported you can perform extended search requestsandWhereClosure $closureWhereQueryIf supported you can perform extended search requestsallWhereQuerySelect all available messagesansweredWhereQuerySelect answered messagesdeletedWhereQuerySelect deleted messagesnewWhereQuerySelect new messagesnotWhereQueryNot select messagesoldWhereQuerySelect old messagesrecentWhereQuerySelect recent messagesseenWhereQuerySelect seen messagesunansweredWhereQuerySelect unanswered messagesundeletedWhereQuerySelect undeleted messagesunflaggedWhereQuerySelect unflagged messagesunseenWhereQuerySelect unseen messagesnoXSpamWhereQuerySelect as no xspam flagged messagesisXSpamWhereQuerySelect as xspam flagged messageslanguagestring $valueWhereQuerySelect messages matching a given languageunkeywordstring $valueWhereQuerySelect messages matching a given unkeywordmessageIdstring $valueWhereQuerySelect messages matching a given message idtostring $valueWhereQuerySelect messages matching a given receiver (To:)textstring $valueWhereQuerySelect messages matching a given text bodysubjectstring $valueWhereQuerySelect messages matching a given subjectsincestring $valueWhereQuerySelect messages since a given dateonstring $valueWhereQuerySelect messages on a given datekeywordstring $valueWhereQuerySelect messages matching a given keywordfromstring $valueWhereQuerySelect messages matching a given sender (From:)flaggedstring $valueWhereQuerySelect messages matching a given flagccstring $valueWhereQuerySelect messages matching a given receiver (CC:)bodystring $valueWhereQuerySelect messages matching a given HTML bodybeforestring $valueWhereQuerySelect messages before a given datebccstring $valueWhereQuerySelect messages matching a given receiver (BCC:)countintegerCount all available messages matching the current search criteriagetMessageCollectionFetch messages with the current querylimitinteger $limit, integer $page = 1WhereQueryLimit the amount of messages being fetchedsetFetchOptionsboolean $fetch\_optionsWhereQuerySet the fetch optionssetFetchBodyboolean $fetch\_bodyWhereQuerySet the fetch body optionsetFetchFlagsboolean $fetch\_flagsWhereQuerySet the fetch flags optionsetFetchOrderstring $fetch\_orderWhereQueryChange the fetch ordering (`asc` is "oldest first", `desc` is "newest first")setFetchOrderAscWhereQueryChange the fetch ordering to ascendingsetFetchOrderDescWhereQueryChange the fetch ordering to descendingleaveUnreadWhereQueryDon't mark all messages as "read" while fetching:markAsReadWhereQueryMark all messages as "read" while fetchingpaginateint $perPage = 5, $page = null, $pageName = 'imap\_page'LengthAwarePaginatorPaginate the current query.### [Attachment::class](src/Attachment.php)

[](#attachmentclass)

MethodArgumentsReturnDescriptiongetContentstring or nullGet attachment contentgetMimeTypestring or nullGet attachment mime typegetExtensionstring or nullGet a guessed attachment extensiongetIdstring or nullGet attachment idgetNamestring or nullGet attachment namegetContentstring or nullGet attachment contentsetSizeint or nullGet attachment sizegetTypestring or nullGet attachment typegetDispositionstring or nullGet attachment dispositiongetContentTypestring or nullGet attachment content typesavestring $path, string $filenamebooleanSave the attachment content to your filesystemmaskstring $mask = nullMaskGet a masked instancesetMaskstring $maskAttachmentSet the mask classgetMaskstringGet the current mask class name### [Mask::class](src/Support/Masks/Mask.php)

[](#maskclass)

MethodArgumentsReturnDescriptiongetParentMasked parentGet the masked parent objectgetAttributesarrayGet all cloned attributes\_\_getmixedAccess any cloned parent attribute\_\_setmixedSet any cloned parent attribute\_\_inheritmixedAll public methods of the given parent are callable### [MessageMask::class](src/Support/Masks/MessageMask.php)

[](#messagemaskclass)

MethodArgumentsReturnDescriptiongetHtmlBodystring or nullGet HTML bodygetCustomHTMLBodycallable or bool $callbackstring or nullGet a custom HTML bodygetHTMLBodyWithEmbeddedBase64Imagesstring or nullGet HTML body with embedded base64 imagesgetHTMLBodyWithEmbeddedUrlImagesstring $route\_name, array $params = \[\]string or nullGet HTML body with embedded routed images### [AttachmentMask::class](src/Support/Masks/AttachmentMask.php)

[](#attachmentmaskclass)

MethodArgumentsReturnDescriptiongetContentBase64Encodedstring or nullGet attachment contentgetImageSrcstring or nullGet attachment mime type### [MessageCollection::class](src/Support/MessageCollection.php)

[](#messagecollectionclass)

Extends [Illuminate\\Support\\Collection::class](https://laravel.com/api/5.4/Illuminate/Support/Collection.html)

MethodArgumentsReturnDescriptionpaginateint $perPage = 15, $page = null, $pageName = 'page'LengthAwarePaginatorPaginate the current collection.### [FlagCollection::class](src/Support/FlagCollection.php)

[](#flagcollectionclass)

Extends [Illuminate\\Support\\Collection::class](https://laravel.com/api/5.4/Illuminate/Support/Collection.html)

MethodArgumentsReturnDescriptionpaginateint $perPage = 15, $page = null, $pageName = 'page'LengthAwarePaginatorPaginate the current collection.### [AttachmentCollection::class](src/Support/AttachmentCollection.php)

[](#attachmentcollectionclass)

Extends [Illuminate\\Support\\Collection::class](https://laravel.com/api/5.4/Illuminate/Support/Collection.html)

MethodArgumentsReturnDescriptionpaginateint $perPage = 15, $page = null, $pageName = 'page'LengthAwarePaginatorPaginate the current collection.### [FolderCollection::class](src/Support/FolderCollection.php)

[](#foldercollectionclass)

Extends [Illuminate\\Support\\Collection::class](https://laravel.com/api/5.4/Illuminate/Support/Collection.html)

MethodArgumentsReturnDescriptionpaginateint $perPage = 15, $page = null, $pageName = 'page'LengthAwarePaginatorPaginate the current collection.### Known issues

[](#known-issues)

ErrorSolutionKerberos error: No credentials cache file found (try running kinit) (...)Uncomment "DISABLE\_AUTHENTICATOR" inside and use the `legacy-imap` protocolChange log
----------

[](#change-log)

Please see [CHANGELOG](https://github.com/Webklex/php-imap/blob/master/CHANGELOG.md) for more information what has changed recently.

Security
--------

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Webklex](https://github.com/webklex)
- [All Contributors](https://github.com/Webklex/php-imap/graphs/contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](https://github.com/Webklex/php-imap/blob/master/LICENSE) for more information.

###  Health Score

30

—

LowBetter than 62% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity8

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity68

Established project with proven stability

 Bus Factor1

Top contributor holds 87.9% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~32 days

Recently: every ~4 days

Total

26

Last Release

2069d ago

Major Versions

0.0.3 → 1.4.22019-07-02

1.4.5 → 2.0.02020-09-20

### Community

Maintainers

![](https://www.gravatar.com/avatar/b4b89fd414bdc5a12a75543759c8353436ec3ba5e75ed51932618fdf798fd337?d=identicon)[smartilabs](/maintainers/smartilabs)

---

Top Contributors

[![Webklex](https://avatars.githubusercontent.com/u/2884144?v=4)](https://github.com/Webklex "Webklex (102 commits)")[![Max13](https://avatars.githubusercontent.com/u/531249?v=4)](https://github.com/Max13 "Max13 (4 commits)")[![smartilabs](https://avatars.githubusercontent.com/u/6381175?v=4)](https://github.com/smartilabs "smartilabs (4 commits)")[![DasTobbel](https://avatars.githubusercontent.com/u/5870230?v=4)](https://github.com/DasTobbel "DasTobbel (3 commits)")[![dwalczyk](https://avatars.githubusercontent.com/u/61882865?v=4)](https://github.com/dwalczyk "dwalczyk (2 commits)")[![Slauta](https://avatars.githubusercontent.com/u/1894301?v=4)](https://github.com/Slauta "Slauta (1 commits)")

---

Tags

mailphp-imapimappop3webklex

### Embed Badge

![Health badge](/badges/smartilabs-php-imap/health.svg)

```
[![Health](https://phpackages.com/badges/smartilabs-php-imap/health.svg)](https://phpackages.com/packages/smartilabs-php-imap)
```

###  Alternatives

[laravel/framework

The Laravel Framework.

34.8k543.8M20.0k](/packages/laravel-framework)[webklex/php-imap

PHP IMAP client

4466.7M27](/packages/webklex-php-imap)[statamic/cms

The Statamic CMS Core Package

4.8k3.6M983](/packages/statamic-cms)[php-imap/php-imap

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

1.7k13.4M52](/packages/php-imap-php-imap)[directorytree/imapengine

A fully-featured IMAP library -- without the PHP extension

551284.6k9](/packages/directorytree-imapengine)[bitrix24/b24phpsdk

An official PHP library for the Bitrix24 REST API

10244.2k5](/packages/bitrix24-b24phpsdk)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
