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

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

saintsloth/ddeboer-imap
=======================

Object-oriented IMAP for PHP

1.0.0(3y ago)02MITPHPPHP ^7.1

Since Nov 25Pushed 3y agoCompare

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

READMEChangelog (1)Dependencies (7)Versions (3)Used By (0)

IMAP library
============

[](#imap-library)

A PHP 7.1+ library to read and process e-mails over IMAP.

This library requires [IMAP](https://secure.php.net/manual/en/book.imap.php), [iconv](https://secure.php.net/manual/en/book.iconv.php) and [Multibyte String](https://secure.php.net/manual/en/book.mbstring.php) extensions installed.

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

[](#table-of-contents)

1. [Feature Requests](#feature-requests)
2. [Installation](#installation)
3. [Usage](#usage)
    1. [Connect and Authenticate](#connect-and-authenticate)
    2. [Mailboxes](#mailboxes)
    3. [Messages](#messages)
        1. [Searching for Messages](#searching-for-messages)
        2. [Unknown search criterion: OR](#unknown-search-criterion-or)
        3. [Message Properties and Operations](#message-properties-and-operations)
    4. [Message Attachments](#message-attachments)
    5. [Embedded Messages](#embedded-messages)
    6. [Timeouts](#timeouts)
4. [Mock the library](#mock-the-library)
5. [Running the Tests](#running-the-tests)
    1. [Running Tests using Docker](#running-tests-using-docker)

Feature Requests
----------------

[](#feature-requests)

[![Feature Requests](https://camo.githubusercontent.com/013717f7adfbd4245be4d644c6bdced345a5d7409b7f3570a9340e5a02b82c32/68747470733a2f2f666561746875622e636f6d2f646465626f65722f696d61703f666f726d61743d737667)](https://feathub.com/ddeboer/imap)

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/Ddeboer/Imap/Message/Headers.php) object:

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

Get message body as HTML or plain text:

```
$message->getBodyHtml();    // Content of text/html part, if present
$message->getBodyText();    // 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);
$connection->expunge();
```

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.

Running the Tests
-----------------

[](#running-the-tests)

This library is functionally tested on [Travis CI](https://travis-ci.org/ddeboer/imap)against a local Dovecot server.

If you have your own IMAP (test) account, you can run the tests locally by providing your IMAP credentials:

```
$ composer install
$ IMAP_SERVER_NAME="my.imap.server.com" IMAP_SERVER_PORT="60993" IMAP_USERNAME="johndoe" IMAP_PASSWORD="p4ssword" vendor/bin/phpunit
```

You can also copy `phpunit.xml.dist` file to a custom `phpunit.xml` and put these environment variables in it:

```

            ./tests/

            ./src

```

**WARNING** Tests create new mailboxes without removing them.

### Running Tests using Docker

[](#running-tests-using-docker)

If you have Docker installed you can run the tests locally with the following command:

```
$ docker-compose run tests

```

###  Health Score

24

—

LowBetter than 32% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity2

Limited adoption so far

Community19

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 59.1% 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

Unknown

Total

1

Last Release

1291d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/13ddc681fe54995b8fc96a3d2018877a1ebbe007360ebdb530bed8cbc79665ef?d=identicon)[saintsloth](/maintainers/saintsloth)

---

Top Contributors

[![Slamdunk](https://avatars.githubusercontent.com/u/152236?v=4)](https://github.com/Slamdunk "Slamdunk (305 commits)")[![ddeboer](https://avatars.githubusercontent.com/u/89267?v=4)](https://github.com/ddeboer "ddeboer (158 commits)")[![trungpv1601](https://avatars.githubusercontent.com/u/25415217?v=4)](https://github.com/trungpv1601 "trungpv1601 (5 commits)")[![wujku](https://avatars.githubusercontent.com/u/1288915?v=4)](https://github.com/wujku "wujku (5 commits)")[![trungpv93](https://avatars.githubusercontent.com/u/7832459?v=4)](https://github.com/trungpv93 "trungpv93 (4 commits)")[![mvar](https://avatars.githubusercontent.com/u/1286752?v=4)](https://github.com/mvar "mvar (3 commits)")[![xelan](https://avatars.githubusercontent.com/u/5080535?v=4)](https://github.com/xelan "xelan (3 commits)")[![krzysiekpiasecki](https://avatars.githubusercontent.com/u/4520629?v=4)](https://github.com/krzysiekpiasecki "krzysiekpiasecki (3 commits)")[![boekkooi](https://avatars.githubusercontent.com/u/399895?v=4)](https://github.com/boekkooi "boekkooi (2 commits)")[![pepamartinec](https://avatars.githubusercontent.com/u/271753?v=4)](https://github.com/pepamartinec "pepamartinec (2 commits)")[![pyatnitsev](https://avatars.githubusercontent.com/u/4361764?v=4)](https://github.com/pyatnitsev "pyatnitsev (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)")[![trizz](https://avatars.githubusercontent.com/u/832056?v=4)](https://github.com/trizz "trizz (2 commits)")[![cabloo](https://avatars.githubusercontent.com/u/229041?v=4)](https://github.com/cabloo "cabloo (2 commits)")[![FlashWS](https://avatars.githubusercontent.com/u/9982293?v=4)](https://github.com/FlashWS "FlashWS (2 commits)")[![OskarStark](https://avatars.githubusercontent.com/u/995707?v=4)](https://github.com/OskarStark "OskarStark (1 commits)")[![burci](https://avatars.githubusercontent.com/u/864531?v=4)](https://github.com/burci "burci (1 commits)")[![Daredzik](https://avatars.githubusercontent.com/u/2691781?v=4)](https://github.com/Daredzik "Daredzik (1 commits)")[![dependabot-preview[bot]](https://avatars.githubusercontent.com/in/2141?v=4)](https://github.com/dependabot-preview[bot] "dependabot-preview[bot] (1 commits)")

---

Tags

mailemailimap

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[ddeboer/imap

Object-oriented IMAP for PHP

9153.9M11](/packages/ddeboer-imap)[zbateson/mail-mime-parser

MIME email message parser

53949.2M79](/packages/zbateson-mail-mime-parser)[henrique-borba/php-sieve-manager

A modern (started in 2022) PHP library for the ManageSieve protocol (RFC5804) to create/edit Sieve scripts (RFC5228). Used by Cypht Webmail.

23125.7k2](/packages/henrique-borba-php-sieve-manager)[opcodesio/mail-parser

Parse emails without the mailparse extension

216.8M8](/packages/opcodesio-mail-parser)[benhall14/php-imap-reader

A PHP class that makes working with IMAP in PHP simple.

3516.6k](/packages/benhall14-php-imap-reader)

PHPackages © 2026

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