PHPackages                             adnanhussainturki/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. adnanhussainturki/imap

ActiveLibrary

adnanhussainturki/imap
======================

Object-oriented IMAP for PHP

053PHP

Since Nov 8Pushed 2y agoCompare

[ Source](https://github.com/AdnanHussainTurki/imap)[ Packagist](https://packagist.org/packages/adnanhussainturki/imap)[ RSS](/packages/adnanhussainturki-imap/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

PHP IMAP library
================

[](#php-imap-library)

[![Latest Stable Version](https://camo.githubusercontent.com/d63c074601e01b51f52552f3801d9b9ec37aca07c7e7e2ea11fd6b5b8061afa3/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f646465626f65722f696d61702e737667)](https://packagist.org/packages/ddeboer/imap)[![Downloads](https://camo.githubusercontent.com/93cba2839c165012e8df424ad3432d666d2010d128243e1a32606ece69812f7d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f646465626f65722f696d61702e737667)](https://packagist.org/packages/ddeboer/imap)[![Integrate](https://github.com/ddeboer/imap/workflows/CI/badge.svg)](https://github.com/ddeboer/imap/actions)[![Code Coverage](https://camo.githubusercontent.com/0800738be023de82b72daf34aee5a6ba0f00c0b805d886e002af5576293d1117/68747470733a2f2f636f6465636f762e696f2f67682f646465626f65722f696d61702f636f7665726167652e7376673f6272616e63683d6d6173746572)](https://codecov.io/gh/ddeboer/imap?branch=master)

A PHP IMAP library to read and process e-mails over IMAP protocol, built with robust Object-Oriented architecture.

This library requires PHP &gt;= 8.1 with [IMAP](https://www.php.net/manual/en/book.imap.php), [iconv](https://www.php.net/manual/en/book.iconv.php) and [Multibyte String](https://www.php.net/manual/en/book.mbstring.php) extensions installed.

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

[](#installation)

The recommended way to install the IMAP library is through [Composer](https://getcomposer.org):

```
$ composer require ddeboer/imap
```

This command requires you to have Composer installed globally, as explained in the [installation chapter](https://getcomposer.org/doc/00-intro.md)of the Composer documentation.

Usage
-----

[](#usage)

### Connect and Authenticate

[](#connect-and-authenticate)

```
use Ddeboer\Imap\Server;

$server = new Server('imap.gmail.com');

// $connection is instance of \Ddeboer\Imap\Connection
$connection = $server->authenticate('my_username', 'my_password');
```

You can specify port, [flags and parameters](https://secure.php.net/manual/en/function.imap-open.php)to the server:

```
$server = new Server(
    $hostname, // required
    $port,     // defaults to '993'
    $flags,    // defaults to '/imap/ssl/validate-cert'
    $parameters
);
```

### Mailboxes

[](#mailboxes)

Retrieve mailboxes (also known as mail folders) from the mail server and iterate over them:

```
$mailboxes = $connection->getMailboxes();

foreach ($mailboxes as $mailbox) {
    // Skip container-only mailboxes
    // @see https://secure.php.net/manual/en/function.imap-getmailboxes.php
    if ($mailbox->getAttributes() & \LATT_NOSELECT) {
        continue;
    }

    // $mailbox is instance of \Ddeboer\Imap\Mailbox
    printf('Mailbox "%s" has %s messages', $mailbox->getName(), $mailbox->count());
}
```

Or retrieve a specific mailbox:

```
$mailbox = $connection->getMailbox('INBOX');
```

Delete a mailbox:

```
$connection->deleteMailbox($mailbox);
```

You can bulk set, or clear, any [flag](https://secure.php.net/manual/en/function.imap-setflag-full.php) of mailbox messages (by UIDs):

```
$mailbox->setFlag('\\Seen \\Flagged', ['1:5', '7', '9']);
$mailbox->setFlag('\\Seen', '1,3,5,6:8');

$mailbox->clearFlag('\\Flagged', '1,3');
```

**WARNING** You must retrieve new Message instances in case of bulk modify flags to refresh the single Messages flags.

### Messages

[](#messages)

Retrieve messages (e-mails) from a mailbox and iterate over them:

```
$messages = $mailbox->getMessages();

foreach ($messages as $message) {
    // $message is instance of \Ddeboer\Imap\Message
}
```

To insert a new message (that just has been sent) into the Sent mailbox and flag it as seen:

```
$mailbox = $connection->getMailbox('Sent');
$mailbox->addMessage($messageMIME, '\\Seen');
```

Note that the message should be a string at MIME format (as described in the [RFC2045](https://tools.ietf.org/html/rfc2045)).

#### Searching for Messages

[](#searching-for-messages)

```
use Ddeboer\Imap\SearchExpression;
use Ddeboer\Imap\Search\Email\To;
use Ddeboer\Imap\Search\Text\Body;

$search = new SearchExpression();
$search->addCondition(new To('me@here.com'));
$search->addCondition(new Body('contents'));

$messages = $mailbox->getMessages($search);
```

**WARNING** We are currently unable to have both spaces *and* double-quotes escaped together. Only spaces are currently escaped correctly. You can use `Ddeboer\Imap\Search\RawExpression` to write the complete search condition by yourself.

Messages can also be retrieved sorted as per [imap\_sort](https://secure.php.net/manual/en/function.imap-sort.php)function:

```
$today = new DateTimeImmutable();
$thirtyDaysAgo = $today->sub(new DateInterval('P30D'));

$messages = $mailbox->getMessages(
    new Ddeboer\Imap\Search\Date\Since($thirtyDaysAgo),
    \SORTDATE, // Sort criteria
    true // Descending order
);
```

#### Unknown search criterion: OR

[](#unknown-search-criterion-or)

Note that PHP imap library relies on the `c-client` library available at which doesn't fully support some IMAP4 search criteria like `OR`. If you want those unsupported criteria, you need to manually patch the latest version (`imap-2007f` of 23-Jul-2011 at the time of this commit) and recompile PHP onto your patched `c-client` library.

By the way most of the common search criteria are available and functioning, browse them in `./src/Search`.

References:

1.
2. imap-2007f.tar.gz: `./src/c-client/mail.c` and `./docs/internal.txt`

#### Message Properties and Operations

[](#message-properties-and-operations)

Get message number and unique [message id](https://en.wikipedia.org/wiki/Message-ID)in the form &lt;...&gt;:

```
$message->getNumber();
$message->getId();
```

Get other message properties:

```
$message->getSubject();
$message->getFrom();    // Message\EmailAddress
$message->getTo();      // array of Message\EmailAddress
$message->getDate();    // DateTimeImmutable
$message->isAnswered();
$message->isDeleted();
$message->isDraft();
$message->isSeen();
```

Get message headers as a [\\Ddeboer\\Imap\\Message\\Headers](/src/Message/Headers.php) object:

```
$message->getHeaders();
```

Get message body as HTML or plain text (only first part):

```
$message->getBodyHtml();    // Content of text/html part, if present
$message->getBodyText();    // Content of text/plain part, if present
```

Get complete body (all parts):

```
$body = $message->getCompleteBodyHtml();    // Content of text/html part, if present
if ($body === null) { // If body is null, there are no HTML parts, so let's try getting the text body
    $body = $message->getCompleteBodyText();    // Content of text/plain part, if present
}
```

Reading the message body keeps the message as unseen. If you want to mark the message as seen:

```
$message->markAsSeen();
```

Or you can set, or clear, any [flag](https://secure.php.net/manual/en/function.imap-setflag-full.php):

```
$message->setFlag('\\Seen \\Flagged');
$message->clearFlag('\\Flagged');
```

Move a message to another mailbox:

```
$mailbox = $connection->getMailbox('another-mailbox');
$message->move($mailbox);
```

Deleting messages:

```
$mailbox->getMessage(1)->delete();
$mailbox->getMessage(2)->delete();
$connection->expunge();
```

### Message Attachments

[](#message-attachments)

Get message attachments (both inline and attached) and iterate over them:

```
$attachments = $message->getAttachments();

foreach ($attachments as $attachment) {
    // $attachment is instance of \Ddeboer\Imap\Message\Attachment
}
```

Download a message attachment to a local file:

```
// getDecodedContent() decodes the attachment’s contents automatically:
file_put_contents(
    '/my/local/dir/' . $attachment->getFilename(),
    $attachment->getDecodedContent()
);
```

### Embedded Messages

[](#embedded-messages)

Check if attachment is embedded message and get it:

```
$attachments = $message->getAttachments();

foreach ($attachments as $attachment) {
    if ($attachment->isEmbeddedMessage()) {
        $embeddedMessage = $attachment->getEmbeddedMessage();
        // $embeddedMessage is instance of \Ddeboer\Imap\Message\EmbeddedMessage
    }
}
```

An EmbeddedMessage has the same API as a normal Message, apart from flags and operations like copy, move or delete.

### Timeouts

[](#timeouts)

The IMAP extension provides the [imap\_timeout](https://secure.php.net/manual/en/function.imap-timeout.php)function to adjust the timeout seconds for various operations.

However the extension's implementation doesn't link the functionality to a specific context or connection, instead they are global. So in order to not affect functionalities outside this library, we had to choose whether wrap every `imap_*` call around an optional user-provided timeout or leave this task to the user.

Because of the heterogeneous world of IMAP servers and the high complexity burden cost for such a little gain of the former, we chose the latter.

Mock the library
----------------

[](#mock-the-library)

Mockability is granted by interfaces present for each API. Dig into [MockabilityTest](tests/MockabilityTest.php) for an example of a mocked workflow.

Contributing: run the build locally
-----------------------------------

[](#contributing-run-the-build-locally)

Docker is needed to run the build on your computer.

First command you need to run is `make start-imap-server`, which starts an IMAP server locally.

Then the local build can be triggered with a bare `make`.

When you finish the development, stop the local IMAP server with `make stop-imap-server`.

###  Health Score

16

—

LowBetter than 5% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity8

Limited adoption so far

Community19

Small or concentrated contributor base

Maturity20

Early-stage or recently created project

 Bus Factor1

Top contributor holds 58.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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/8f093c06ab5970c00e683078ba0e3d7c27ca37e7ed22c9ee1dd94f318868167e?d=identicon)[AdnanHussainTurki](/maintainers/AdnanHussainTurki)

---

Top Contributors

[![Slamdunk](https://avatars.githubusercontent.com/u/152236?v=4)](https://github.com/Slamdunk "Slamdunk (308 commits)")[![ddeboer](https://avatars.githubusercontent.com/u/89267?v=4)](https://github.com/ddeboer "ddeboer (158 commits)")[![wujku](https://avatars.githubusercontent.com/u/1288915?v=4)](https://github.com/wujku "wujku (5 commits)")[![trungpv1601](https://avatars.githubusercontent.com/u/25415217?v=4)](https://github.com/trungpv1601 "trungpv1601 (5 commits)")[![trungpv93](https://avatars.githubusercontent.com/u/7832459?v=4)](https://github.com/trungpv93 "trungpv93 (4 commits)")[![xelan](https://avatars.githubusercontent.com/u/5080535?v=4)](https://github.com/xelan "xelan (3 commits)")[![mvar](https://avatars.githubusercontent.com/u/1286752?v=4)](https://github.com/mvar "mvar (3 commits)")[![krzysiekpiasecki](https://avatars.githubusercontent.com/u/4520629?v=4)](https://github.com/krzysiekpiasecki "krzysiekpiasecki (3 commits)")[![AdnanHussainTurki](https://avatars.githubusercontent.com/u/24974673?v=4)](https://github.com/AdnanHussainTurki "AdnanHussainTurki (2 commits)")[![cabloo](https://avatars.githubusercontent.com/u/229041?v=4)](https://github.com/cabloo "cabloo (2 commits)")[![arwinvdv](https://avatars.githubusercontent.com/u/7255485?v=4)](https://github.com/arwinvdv "arwinvdv (2 commits)")[![pyatnitsev](https://avatars.githubusercontent.com/u/4361764?v=4)](https://github.com/pyatnitsev "pyatnitsev (2 commits)")[![pepamartinec](https://avatars.githubusercontent.com/u/271753?v=4)](https://github.com/pepamartinec "pepamartinec (2 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (2 commits)")[![FlashWS](https://avatars.githubusercontent.com/u/9982293?v=4)](https://github.com/FlashWS "FlashWS (2 commits)")[![trizz](https://avatars.githubusercontent.com/u/832056?v=4)](https://github.com/trizz "trizz (2 commits)")[![jakubboucek](https://avatars.githubusercontent.com/u/1657322?v=4)](https://github.com/jakubboucek "jakubboucek (2 commits)")[![LeadTechVisas](https://avatars.githubusercontent.com/u/44460455?v=4)](https://github.com/LeadTechVisas "LeadTechVisas (2 commits)")[![nikoskip](https://avatars.githubusercontent.com/u/1230033?v=4)](https://github.com/nikoskip "nikoskip (2 commits)")[![boekkooi](https://avatars.githubusercontent.com/u/399895?v=4)](https://github.com/boekkooi "boekkooi (2 commits)")

### Embed Badge

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

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

PHPackages © 2026

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