ImapEngine
repository·master·Indexed 20 days ago
https://github.com/directorytree/imapengineA 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.
What's inside ImapEngine
- 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.
Use logical operators and nested conditions
masterThe
ImapQueryBuilderallows for complex logical grouping:where(mixed $column, mixed $value = null): Adds anANDcondition. If$columnis acallable, it creates a nested condition group.orWhere(mixed $column, mixed $value = null): Adds anORcondition. If$columnis acallable, it creates a nested condition group.whereNot(mixed $column, mixed $value = null): Adds anAND NOTcondition.
Example of nested conditions:
$query = (new ImapQueryBuilder()) ->where(function (ImapQueryBuilder $query) { $query->from('boss@company.com') ->subject('Urgent'); }) ->orWhere('flagged');Configure Greenmail via Docker Compose
masterGreenmail 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
3143to the host. You can configure the server behavior using theGREENMAIL_OPTSenvironment variable.Common configuration flags for
GREENMAIL_OPTSinclude:-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"Configure the Mailbox connection
masterThe
Mailboxclass is initialized with a configuration array. You can use theconfig()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. Useoauthfor OAuth2 orplainfor standard login (default:plain).debug(mixed): Enables debugging. Can be abool(iftrue, usesEchoLogger), astring(path to a file forFileLogger), 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', ]);Identify attachment and inline parts using BodyStructurePart
masterYou can use the following methods on a
BodyStructurePartinstance to determine how a part should be handled:isAttachment(): Returnstrueif the part is an attachment. It considers theContentDisposition, but also treats non-text/html parts with a filename as attachments.isInline(): Returnstrueif the part is marked as inline via its disposition.isText(): Returnstrueif the type istextand subtype isplain.isHtml(): Returnstrueif the type istextand subtype ishtml.
Manage message flags
masterYou 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: ABackedEnumorstringrepresenting the flag.$operation: A string indicating the operation:'+'to add a flag or'-'to remove a flag.$expunge: (Optional) Iftrue, callsexpunge()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);Inspect properties of a BodyStructurePart
masterThe
BodyStructurePartclass 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 aContentDispositionobject.charset(): Returns the character set from the parameters.
Retrieve message headers and identity
masterThe
Messageclass provides high-level methods to extract common email headers. Most methods accept a$fetchparameter 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 aCarbonInterfaceobject.messageId(bool $fetch = false): Returns theMessage-IDheader value.from(bool $fetch = false): Returns theFromaddress as anAddressobject.to(bool $fetch = false): Returns an array ofAddressobjects for theToheader.cc(bool $fetch = false): Returns an array ofAddressobjects for theCcheader.bcc(bool $fetch = false): Returns an array ofAddressobjects for theBccheader.replyTo(bool $fetch = false): Returns theReply-Toaddress.inReplyTo(bool $fetch = false): Returns an array ofMessage-IDstrings from theIn-Reply-Toheader.
Filter by UID, size, or range
masterUse these methods for technical filtering:
uid(int|string|array $from, int|float|null $to = null): Search within a range of UIDs. If$toisINF, 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.
Build IMAP search queries with ImapQueryBuilder
masterThe
ImapQueryBuilderprovides 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. UseisEmpty()to check if any conditions have been added.$query = (new ImapQueryBuilder()) ->from('user@example.com') ->subject('Hello') ->since('2023-01-01') ->toImap();Parse email body structure with BodyStructurePart::fromListData()
masterUse the
BodyStructurePart::fromListData()static method to convert IMAPListDataobjects (representing aBODYSTRUCTUREresponse) into a structuredBodyStructurePartinstance. 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 providedListDatatokens.contentType(): Returns the full MIME type string (e.g.,text/html).isAttachment(): Returnstrueif 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 thenameparameter.
// 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(); }Generate pagination URLs with LengthAwarePaginator
masterYou can generate URLs for navigating through pages using the following methods. These URLs will automatically include the
path, thequeryparameters provided during construction, and thepageNameparameter.url(int $page): Generates a URL for a specific page number.nextPageUrl(): Returns the URL for the next page, ornullif no more pages exist.previousPageUrl(): Returns the URL for the previous page, ornullif on the first page.
// Example of generating navigation links $next = $paginator->nextPageUrl(); $prev = $paginator->previousPageUrl(); $pageThree = $paginator->url(3);