Search by

ajenbo / imap.php

AJenbo

IMAP over socket

Package info

github.com/AJenbo/Imap.php

pkg:composer/ajenbo/imap.php

Statistics

Installs: 723

Dependents: 0

Suggesters: 0

Stars: 12

Open Issues: 0

1.0.0 2026-12-01 12:36 UTC

This package is auto-updated.

Last update: 2026-12-01 12:48:56 UTC


README

Codacy Badge

This is a rewrite of the class found at http://www.phpclasses.org/package/2351-PHP-Access-IMAP-mailboxes-without-PHP-IMAP-extension.html as I found it lacking in some aspects and overreaching in others.

It accesses the IMAP server using a TCP socket without using the PHP IMAP extension, which is no longer bundled with PHP since 8.4.

It provides functions for:

  • Authenticating (PLAIN with or without SASL-IR, LOGIN, or the LOGIN command)
  • Get server capabilities
  • Listing, creating, renaming and deleting mailboxes
  • Manage mailbox subscriptions
  • Getting mailbox status
  • Uploading mails to a mailbox
  • Search for mails
  • Retrieving mail, with the envelope and MIME structure parsed
  • Managing mail flags
  • Copying and moving messages
  • Delete mail

Installation

Requires PHP 8.1 or later with mbstring, and openssl for TLS connections.

composer require ajenbo/imap.php

Usage

use AJenbo\Imap;

// Use ssl:// and port 993 for TLS, a plain host name for port 143
$imap = new Imap('user@example.com', 'password', 'ssl://imap.example.com', 993);

$imap->select('INBOX');
$uids = $imap->search('UNSEEN', true);

if ($uids) {
    $messages = $imap->fetch(implode(',', $uids), '(ENVELOPE BODYSTRUCTURE)', true);
    foreach ($messages as $uid => $message) {
        echo mb_decode_mimeheader($message['ENVELOPE']['subject'] ?? ''), "\n";

        // Every part of the structure has the section to fetch it with
        $part = $message['BODYSTRUCTURE'];
        while ($part['type'] === 'multipart') {
            $part = $part['parts'][0];
        }

        // BODY.PEEK leaves the message unread
        $section = 'BODY[' . $part['section'] . ']';
        $body = $imap->fetch((string) $uid, 'BODY.PEEK[' . $part['section'] . ']', true)[$uid][$section];
        if ($part['encoding'] === 'base64') {
            $body = base64_decode($body);
        } elseif ($part['encoding'] === 'quoted-printable') {
            $body = quoted_printable_decode($body);
        }
    }
}

$imap->move('4827', 'Archive', true);

$imap->logout();

fetch() returns the data items for each message by name, keyed by UID when $uid is set and by sequence number otherwise:

[
    4827 => [
        'UID'           => 4827,
        'FLAGS'         => ['\Seen' => true],
        'INTERNALDATE'  => '17-Jul-1996 02:44:25 -0700',
        'RFC822.SIZE'   => 4286,
        'ENVELOPE'      => [
            'date'        => 'Wed, 17 Jul 1996 02:23:25 -0700 (PDT)',
            'subject'     => 'Meeting',
            'from'        => [['name' => 'Terry Gray', 'adl' => null, 'mailbox' => 'gray', 'host' => 'example.com']],
            // sender, reply-to, to, cc and bcc like from
            'in-reply-to' => null,
            'message-id'  => '<B27397-0100000@example.com>',
        ],
        'BODYSTRUCTURE' => [
            'type'    => 'multipart',
            'subtype' => 'alternative',
            'section' => '',
            'parts'   => [
                [
                    'type'       => 'text',
                    'subtype'    => 'plain',
                    'parameters' => ['charset' => 'utf-8'],
                    'encoding'   => 'quoted-printable',
                    'size'       => 1234,
                    'lines'      => 30,
                    'section'    => '1',
                    // id, description, md5, disposition, language and location
                ],
                // ...
            ],
            // parameters, disposition, language and location
        ],
        'BODY[HEADER]'  => "From: ...",
    ],
]

Strings in ENVELOPE are as they are in the message header, use mb_decode_mimeheader() to decode words like =?UTF-8?Q?...?=.

Errors

Methods throw AJenbo\Imap\Exception if the server answers NO or BAD (the message is the server's response), and if the connection fails or times out. After a NO or BAD the connection can still be used.

To connect in some other way, for example with custom TLS settings, extend the class and override openSocket():

class MyImap extends AJenbo\Imap
{
    protected function openSocket(string $host, int $port, int $timeout)
    {
        $context = stream_context_create(['ssl' => ['cafile' => '/path/to/ca.pem']]);
        $socket = stream_socket_client($host . ':' . $port, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $context);
        if (!$socket) {
            throw new AJenbo\Imap\Exception($errstr);
        }

        return $socket;
    }
}

Development

composer install
composer test
composer analyse