ImapEngine

repository·master·Indexed 20 days ago

https://github.com/directorytree/imapengine

A PHP library for simplifying mailbox management via the IMAP protocol. It provides a high-level API that functions independently of the native PHP IMAP extension, featuring a fluent ImapQueryBuilder for complex searches, tools for parsing multipart MIME email structures via BodyStructureCollection and BodyStructurePart, and utilities for extracting and managing email attachments.

Tokens
8.1K
Snippets
25
Records
40
Agent score
69%

What's inside ImapEngine

  1. Overview of ImapEngine

    master
    ImapEngine is a PHP library that provides a simple API for managing mailboxes via the IMAP protocol. A key advantage of ImapEngine is that it allows you to work with IMAP without requiring the installation of the PHP IMAP extension.
  2. Use logical operators and nested conditions

    master

    The ImapQueryBuilder allows for complex logical grouping:

    • where(mixed $column, mixed $value = null): Adds an AND condition. If $column is a callable, it creates a nested condition group.
    • orWhere(mixed $column, mixed $value = null): Adds an OR condition. If $column is a callable, it creates a nested condition group.
    • whereNot(mixed $column, mixed $value = null): Adds an AND NOT condition.

    Example of nested conditions:

    $query = (new ImapQueryBuilder())
        ->where(function (ImapQueryBuilder $query) {
            $query->from('boss@company.com')
                  ->subject('Urgent');
        })
        ->orWhere('flagged');
  3. Configure Greenmail via Docker Compose

    master

    Greenmail can be run as a standalone service using Docker Compose. This service provides a mock IMAP/SMTP server for testing purposes.

    By default, the service maps port 3143 to the host. You can configure the server behavior using the GREENMAIL_OPTS environment variable.

    Common configuration flags for GREENMAIL_OPTS include:

    • -Dgreenmail.setup.test.all: Sets up all test protocols.
    • -Dgreenmail.hostname=0.0.0.0: Binds the server to all network interfaces.
    • -Dgreenmail.auth.disabled: Disables authentication requirements.
    • -Dgreenmail.verbose: Enables verbose logging.
    services:
        greenmail:
            image: greenmail/standalone:latest
            environment:
                - GREENMAIL_OPTS=-Dgreenmail.setup.test.all -Dgreenmail.hostname=0.0.0.0 -Dgreenmail.auth.disabled -Dgreenmail.verbose
            ports:
                - "3143:3143"
  4. Configure the Mailbox connection

    master

    The Mailbox class is initialized with a configuration array. You can use the config() method to retrieve specific keys or the entire configuration set.

    Available configuration keys:

    • host (string): The IMAP server hostname.
    • port (int): The connection port (default: 993).
    • username (string): The IMAP username.
    • password (string): The IMAP password.
    • timeout (int): Connection timeout in seconds (default: 30).
    • encryption (string): Encryption type (e.g., ssl).
    • validate_cert (bool): Whether to validate the SSL certificate (default: true).
    • authentication (string): Authentication method. Use oauth for OAuth2 or plain for standard login (default: plain).
    • debug (mixed): Enables debugging. Can be a bool (if true, uses EchoLogger), a string (path to a file for FileLogger), or a class name for a custom logger.
    • proxy (array): Proxy settings containing:
      • socket (string|null): The proxy socket.
      • username (string|null): Proxy username.
      • password (string|null): Proxy password.
      • request_fulluri (bool): Whether to request full URIs.
    $mailbox = Mailbox::make([
        'host' => 'imap.example.com',
        'port' => 993,
        'username' => 'user@example.com',
        'password' => 'password',
        'encryption' => 'ssl',
        'debug' => '/path/to/debug.log',
    ]);
  5. Identify attachment and inline parts using BodyStructurePart

    master

    You can use the following methods on a BodyStructurePart instance to determine how a part should be handled:

    • isAttachment(): Returns true if the part is an attachment. It considers the ContentDisposition, but also treats non-text/html parts with a filename as attachments.
    • isInline(): Returns true if the part is marked as inline via its disposition.
    • isText(): Returns true if the type is text and subtype is plain.
    • isHtml(): Returns true if the type is text and subtype is html.
  6. Manage message flags

    master

    You can add or remove flags from a message using the flag() method. This operation is performed on the server via the mailbox connection.

    Parameters:

    • $flag: A BackedEnum or string representing the flag.
    • $operation: A string indicating the operation: '+' to add a flag or '-' to remove a flag.
    • $expunge: (Optional) If true, calls expunge() on the folder after the operation.

    Example:

    // Add the 'Seen' flag and expunge the folder
    $message->flag('Seen', '+', expunge: true);
    
    // Remove the 'Deleted' flag
    $message->flag('Deleted', '-');
    $message->flag('Seen', '+', expunge: true);
  7. Inspect properties of a BodyStructurePart

    master

    The BodyStructurePart class provides methods to access metadata about a specific part of an email's body structure.

    Available Metadata Methods

    • partNumber(): Returns the part identifier (e.g., 1, 1.2).
    • type(): Returns the MIME type (e.g., text, image, multipart).
    • subtype(): Returns the MIME subtype (e.g., plain, html, jpeg).
    • parameters(): Returns an associative array of all MIME parameters.
    • parameter(string $name): Returns a specific parameter value by name (case-insensitive).
    • id(): Returns the content ID.
    • description(): Returns the decoded MIME description.
    • encoding(): Returns the content transfer encoding.
    • size(): Returns the size in bytes.
    • lines(): Returns the number of lines (for text parts).
    • disposition(): Returns a ContentDisposition object.
    • charset(): Returns the character set from the parameters.
  8. Retrieve message headers and identity

    master

    The Message class provides high-level methods to extract common email headers. Most methods accept a $fetch parameter to trigger a server request if headers aren't loaded.

    • subject(bool $fetch = false): Returns the email subject.
    • date(bool $fetch = false): Returns the message date as a CarbonInterface object.
    • messageId(bool $fetch = false): Returns the Message-ID header value.
    • from(bool $fetch = false): Returns the From address as an Address object.
    • to(bool $fetch = false): Returns an array of Address objects for the To header.
    • cc(bool $fetch = false): Returns an array of Address objects for the Cc header.
    • bcc(bool $fetch = false): Returns an array of Address objects for the Bcc header.
    • replyTo(bool $fetch = false): Returns the Reply-To address.
    • inReplyTo(bool $fetch = false): Returns an array of Message-ID strings from the In-Reply-To header.
  9. Filter by UID, size, or range

    master

    Use these methods for technical filtering:

    • uid(int|string|array $from, int|float|null $to = null): Search within a range of UIDs. If $to is INF, it defaults to the maximum allowed IMAP UID (4294967295).
    • larger(int $bytes): Messages larger than the specified number of bytes.
    • smaller(int $bytes): Messages smaller than the specified number of bytes.
  10. Build IMAP search queries with ImapQueryBuilder

    master

    The ImapQueryBuilder provides a fluent interface for constructing complex IMAP search queries. It supports basic conditions (AND), OR conditions, and nested condition groups. You can chain various methods to filter emails by status, sender, recipient, date, subject, or specific headers.

    To generate the final IMAP-compatible string, call the toImap() method. Use isEmpty() to check if any conditions have been added.

    $query = (new ImapQueryBuilder())
        ->from('user@example.com')
        ->subject('Hello')
        ->since('2023-01-01')
        ->toImap();
  11. Parse email body structure with BodyStructurePart::fromListData()

    master

    Use the BodyStructurePart::fromListData() static method to convert IMAP ListData objects (representing a BODYSTRUCTURE response) into a structured BodyStructurePart instance. This allows you to programmatically inspect the MIME type, size, encoding, and disposition of specific email parts.

    Key Methods

    • fromListData(ListData $data, string $partNumber = '1'): Creates a new instance from the provided ListData tokens.
    • contentType(): Returns the full MIME type string (e.g., text/html).
    • isAttachment(): Returns true if the part is an attachment based on disposition or the presence of a filename for non-text parts.
    • isHtml() / isText(): Helper methods to identify text-based content types.
    • filename(): Retrieves the filename from the content disposition or the name parameter.
    // Example usage (conceptual):
    $part = BodyStructurePart::fromListData($listData, '1.2');
    
    echo $part->contentType(); // e.g., 'image/jpeg'
    echo $part->size();       // e.g., 1024
    if ($part->isAttachment()) {
        echo 'Filename: ' . $part->filename();
    }
  12. Generate pagination URLs with LengthAwarePaginator

    master

    You can generate URLs for navigating through pages using the following methods. These URLs will automatically include the path, the query parameters provided during construction, and the pageName parameter.

    • url(int $page): Generates a URL for a specific page number.
    • nextPageUrl(): Returns the URL for the next page, or null if no more pages exist.
    • previousPageUrl(): Returns the URL for the previous page, or null if on the first page.
    // Example of generating navigation links
    $next = $paginator->nextPageUrl();
    $prev = $paginator->previousPageUrl();
    $pageThree = $paginator->url(3);