php-imap

repository·master·Indexed 23 days ago

https://github.com/barbushin/php-imap

A high-level object-oriented PHP library for connecting to mailboxes via POP3, IMAP, and NNTP using the ext-imap extension. It provides tools for fetching, searching, and managing emails, attachments, and headers, with support for OAuth2 authentication and inline image embedding.

Tokens
4.1K
Snippets
5
Records
31
Agent score
83%

What's inside php-imap

  1. Install php-imap via Composer

    master

    Install the latest stable release of php-imap using Composer. Ensure that the PHP ext-imap extension is already installed and enabled for your PHP version before running the command.

    $ composer require php-imap/php-imap

    To install the latest development version from the master branch:

    $ composer require php-imap/php-imap:dev-master
  2. Run php-imap tests

    master

    To run tests, ensure you have a working ext-imap installation and have run composer install to install development dependencies.

    Run all tests (using composer):

    composer run tests

    Run only PHPUnit tests:

    php vendor/bin/phpunit --testdox
    # Run all tests
    composer run tests
    
    # Run only PHPUnit tests
    php vendor/bin/phpunit --testdox
  3. Configure PHP environment requirements

    master

    To use php-imap, your PHP environment must meet the following requirements:

    • Required Extensions: ext-imap, fileinfo, iconv, mbstring, and json.
    • PHP Version Support:
      • PHP 8.2, 8.3, 8.4, and 8.5 are supported by version 6.x (Active support).
    • IMAP Installation by Version:
      • PHP 8.2 & 8.3: Install or enable the IMAP extension provided by your PHP distribution (e.g., extension=php_imap.dll on Windows).
      • PHP 8.4+: Install IMAP from PECL and enable it for both CLI and web SAPIs.
    • Build Dependencies (if building from source): c-client, OpenSSL, and Kerberos development libraries.
    • Note: ext-imap is not thread-safe and should not be used with ZTS (Zend Thread Safety) builds.
  4. Use PhpImap\Mailbox to fetch emails

    master

    The PhpImap\Mailbox class is the primary entry point for interacting with mailboxes via POP3, IMAP, or NNTP.

    Basic Initialization

    When instantiating Mailbox, you can specify the server connection string, credentials, an attachment directory, and encoding.

    Attachment Management

    • Filename Mode: By default, attachments use random filenames to prevent overwriting. Set the last argument of the constructor to true to use original filenames.
    • Collision Handling: To prevent overwriting existing files with the same name, use setAttachmentFilenameCollisionMode with PhpImap\Mailbox::ATTACHMENT_FILENAME_COLLISION_SUFFIX to automatically append suffixes like (1), (2), etc.
    • Performance: If you do not need to download attachments, call $mailbox->setAttachmentsIgnore(true) to significantly increase performance.

    Searching and Retrieving

    • Use searchMailbox($criteria) to find email IDs. The criteria follow PHP's imap_search documentation.
    • Use getMail($id) to retrieve a message object. To inspect a message without marking it as 'seen', use getMail($id, false).

    Accessing Email Data

    Once you have a mail object, you can check for attachments with hasAttachments(), retrieve them with getAttachments(), or access headers using getHeader($name) or getHeaders($name).

  5. Initialize the Mailbox class

    master

    To interact with an IMAP mailbox, instantiate the PhpImap\Mailbox class. The constructor requires the IMAP path, login, and password. You can optionally configure an attachments directory, server encoding, and attachment filename mode.

    Constructor Parameters:

    • string $imapPath: The IMAP connection path (e.g., {imap.example.com:993/imap/ssl}INBOX).
    • string $login: The email address or login identifier.
    • string $password: The password or access token.
    • ?string $attachmentsDir: (Optional) A directory where attachments will be saved.
    • string $serverEncoding: (Optional) The server encoding, defaults to 'UTF-8'.
    • bool $trimImapPath: (Optional) Whether to trim the imap path, defaults to true.
    • bool $attachmentFilenameMode: (Optional) Whether to use original filenames, defaults to false.
  6. Enable OAuth2 authentication

    master

    If your provider requires OAuth instead of a password, you can enable it explicitly. You must obtain and refresh the access token outside of this library. Note that your ext-imap build must expose OP_XOAUTH2 for this to work.

    $mailbox->enableOAuth($accessToken);
  7. Call native PHP IMAP functions via Mailbox

    master

    The imap() method allows you to call any native PHP IMAP function within the context of your Mailbox instance. This is useful for operations not explicitly wrapped by the library.

    Example calling imap_check():

    $info = $mailbox->imap('check');
    // Call imap_check() - see http://php.net/manual/function.imap-check.php
    $info = $mailbox->imap('check');
  8. Replace internal HTML links with base URIs

    master

    The replaceInternalLinks(string $baseUri) method is used to transform internal cid: links in the HTML body into absolute URLs.

    1. It identifies placeholders using getInternalLinksPlaceholders().
    2. It matches these placeholders against the current attachments.
    3. It replaces the placeholder with $baseUri concatenated with the basename of the attachment's file path.

    Example: If $baseUri is https://example.com/files/ and an attachment has filename image.png, the cid: link will be replaced by https://example.com/files/image.png.

  9. Access attachment properties in IncomingMailAttachment

    master

    The IncomingMailAttachment class provides several public properties to inspect the metadata of an email attachment. These include:

    • $id: Attachment ID
    • $contentId: Content ID
    • $type: MIME type integer
    • $encoding: Encoding type
    • $subtype: MIME subtype
    • $description: Attachment description
    • $name: Filename
    • $sizeInBytes: Size in bytes
    • $disposition: Disposition (e.g., attachment, inline)
    • $charset: Character set
    • $emlOrigin: Whether it originated from an EML file
    • $fileInfoRaw: Raw file info
    • $fileInfo: Formatted file info
    • $mime: MIME string
    • $mimeEncoding: MIME encoding
    • $fileExtension: File extension
    • $mimeType: MIME type string
  10. Get mail headers with getMailHeader()

    master

    To retrieve the metadata of a message, use getMailHeader(int $mailId). This returns an IncomingMailHeader object containing parsed information such as:

    • subject (decoded)
    • from, to, cc, bcc, replyTo (parsed into host, name, and address)
    • date (parsed into a DateTime object)
    • Flags like isSeen, isAnswered, isFlagged, etc.
    • Custom headers like X-Mailer, X-Virus-Scanned, etc.
  11. Embed inline images as Base64 in HTML

    master
    The embedImageAttachments() method scans the textHtml body for cid: (Content-ID) references. If a matching attachment is found that is an image, it replaces the cid: reference with a Base64 encoded data URI (e.g., data:image/png;base64,...). This allows HTML emails to display inline images without external links. After embedding, the attachment is removed from the mail's attachment list.