### Install ImapEngine Laravel Package Source: https://imapengine.com/docs/laravel/installation Use Composer to install the ImapEngine Laravel package. Ensure PHP 8.1+ and Laravel 10.0+ are met. ```bash composer require directorytree/imapengine-laravel ``` -------------------------------- ### Install ImapEngine via Composer Source: https://imapengine.com/docs/installation Use this Composer command to add ImapEngine to your project dependencies. Ensure you have PHP 8.1 or higher installed. ```bash composer require directorytree/imapengine ``` -------------------------------- ### Setup Fake Mailbox for Pest Tests Source: https://imapengine.com/docs/usage/testing Use this setup in your Pest tests to create a fake mailbox with pre-defined folders and messages. Ensure the necessary fake classes are imported. ```php use DirectoryTree\ImapEngine\Testing\FakeFolder; use DirectoryTree\ImapEngine\Testing\FakeMailbox; use DirectoryTree\ImapEngine\Testing\FakeMessage; beforeEach(function () { // Create a fake mailbox for testing $this->mailbox = new FakeMailbox( config: ['host' => 'imap.example.com', 'port' => 993], folders: [ new FakeFolder( path: 'inbox', messages: [ new FakeMessage( uid: 1, flags: ['\Seen'], contents: 'From: sender@example.com\r\nTo: recipient@example.com\r\nSubject: Test Email\r\n\r\nThis is a test email.' ) ] ) ] ); }); ``` -------------------------------- ### Process Messages with Attachments Source: https://imapengine.com/docs/usage/messages An example demonstrating how to fetch messages with their body structure and then check for and count attachments. ```php $messages = $inbox->messages() ->withBodyStructure() ->get(); foreach ($messages as $message) { $structure = $message->bodyStructure(); // Check if message has attachments if ($structure->hasAttachments()) { echo "Message has {$structure->attachmentCount()} attachment(s)\n"; ``` -------------------------------- ### Start Awaiting New Messages with IDLE Source: https://imapengine.com/docs/usage/monitoring Initiates the IDLE command to receive push notifications for new messages. This method is blocking and should be run in a background process. ```php use DirectoryTree\ImapEngine\Message; // Get the inbox folder $inbox = $mailbox->inbox(); // Begin idling on the inbox folder. $inbox->idle(function (Message $message) { // Do something with the newly received message }); ``` -------------------------------- ### Connect to IMAP Server and Retrieve Messages Source: https://imapengine.com/ Connect to an IMAP server using SSL and retrieve all messages from the inbox, including their headers. This example demonstrates basic connection and message retrieval. ```php use DirectoryTree\ImapEngine\Mailbox; $mailbox = new Mailbox([ 'host' => 'imap.example.com', 'port' => 993, 'encryption' => 'ssl', 'username' => 'user@example.com', 'password' => 'password', ]); $inbox = $mailbox->inbox(); $messages = $inbox->messages()->get(); ``` ```php use DirectoryTree\ImapEngine\Mailbox; $mailbox = new Mailbox([ 'host' => 'imap.example.com', 'port' => 993, 'encryption' => 'ssl', 'username' => 'user@example.com', 'password' => 'password' ]); // Get the inbox folder $inbox = $mailbox->inbox(); // Get all messages in the inbox $messages = $inbox->messages() ->withHeaders() ->get(); foreach ($messages as $message) { echo $message->from()->email(); } ``` -------------------------------- ### Get All Multipart Message Parameters Source: https://imapengine.com/docs/usage/messages Access all parameters associated with a multipart message, such as the boundary, using the `parameters()` method. ```php $structure = $message->bodyStructure(); // Get all parameters $structure->parameters(); // ['boundary' => 'Aq14h3UL'] ``` -------------------------------- ### Retrieving Folders Source: https://imapengine.com/docs/usage/folders This section covers how to get all folders or folders matching a specific pattern from an IMAP mailbox. ```APIDOC ## Retrieving Folders ### Description To retrieve folders from an IMAP mailbox, you may use the `folders()` method on the `Mailbox` instance. This method returns a `FolderRepository` instance, which provides operations for retrieving, creating, and managing folders. ### Method `folders()` ### Endpoint N/A (Method on Mailbox instance) ### Parameters None ### Request Example ```php use DirectoryTree\ImapEngine\Mailbox; $mailbox = new Mailbox([ // ... ]); // Get all folders. $folders = $mailbox->folders()->get(); // Get folders matching a glob pattern. $folders = $mailbox->folders()->get('*/Subfolder'); ``` ### Response #### Success Response (200) - **folders** (FolderRepository) - An instance of FolderRepository to perform folder operations. #### Response Example (Returns a FolderRepository instance, actual folder data is retrieved via subsequent calls like `get()`) ``` -------------------------------- ### Retrieve All Headers Source: https://imapengine.com/docs/usage/messages Get an array of all headers from a `Message` object using the `headers()` method. ```php $message->headers(): IHeader[] ``` -------------------------------- ### Retrieve Mailbox Server Capabilities Source: https://imapengine.com/docs/usage/connecting Get a list of supported IMAP capabilities advertised by the mailbox server by calling the `capabilities()` method. ```php // ["IMAP4rev1", "IDLE", "UIDPLUS", ...] $capabilities = $mailbox->capabilities(); ``` -------------------------------- ### Getting Specific Folders Source: https://imapengine.com/docs/usage/folders Learn how to find a specific folder by name, retrieve the inbox folder directly, or find and fail if the folder does not exist. ```APIDOC ## Getting a Specific Folder ### Description To retrieve a specific folder, you may use the `find()` method on the `FolderRepository` instance. The `inbox()` method provides a shortcut to get the mandatory inbox folder. ### Method `inbox()`, `find(string $name)`, `findOrFail(string $name)` ### Endpoint N/A (Methods on Mailbox or FolderRepository instances) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php // Get the inbox folder. $inbox = $mailbox->inbox(); // Find a specific folder by name. $folder = $mailbox->folders()->find('Sent'); // Find a folder or fail (throw an exception). $folder = $mailbox->folders()->findOrFail('Important'); ``` ### Response #### Success Response (200) - **folder** (Folder) - An instance of the Folder class representing the found folder. #### Response Example (Returns a Folder instance or throws an exception if not found with `findOrFail`) ``` -------------------------------- ### Configure IMAP Mailbox Connection Source: https://imapengine.com/docs/installation Instantiate the Mailbox class with your IMAP server details. This basic example includes essential connection parameters like host, port, username, password, and encryption. ```php use DirectoryTree\ImapEngine\Mailbox; $mailbox = new Mailbox([ 'port' => 993, 'username' => 'your-username', 'password' => 'your-password', 'encryption' => 'ssl', 'host' => 'imap.example.com', ]); ``` -------------------------------- ### Get Content ID and Description of Individual Part Source: https://imapengine.com/docs/usage/messages Retrieve the content ID (e.g., '') and description of an individual message part using the `id()` and `description()` methods. ```php $part = $structure->text(); // Get content ID and description $part->id(); // "" $part->description(); // "Message body" ``` -------------------------------- ### Get Charset from Individual Part Source: https://imapengine.com/docs/usage/messages Conveniently retrieve the charset parameter for a text part using the `charset()` method. ```php $part = $structure->text(); // Get the charset $part->charset(); // "utf-8" ``` -------------------------------- ### Get Individual Part Parameters Source: https://imapengine.com/docs/usage/messages Access all parameters associated with an individual message part, such as 'charset', using the `parameters()` method. ```php $part = $structure->text(); // Get parameters (e.g., charset) $part->parameters(); // ['charset' => 'utf-8'] ``` -------------------------------- ### Get Line Count of Text Part Source: https://imapengine.com/docs/usage/messages For text parts, retrieve the number of lines using the `lines()` method. ```php $part = $structure->text(); // Get line count (for text parts) $part->lines(); // 50 (for text parts) ``` -------------------------------- ### PHPUnit Test with Fake Mailbox Source: https://imapengine.com/docs/usage/testing Integrate ImapEngine's testing utilities into your PHPUnit tests by setting up a `FakeMailbox` in the `setUp` method. This allows you to simulate email scenarios and test your processing logic. ```php use PHPUnit\Framework\TestCase; use DirectoryTree\ImapEngine\Testing\FakeFolder; use DirectoryTree\ImapEngine\Testing\FakeMailbox; use DirectoryTree\ImapEngine\Testing\FakeMessage; class EmailProcessorTest extends TestCase { protected function setUp(): void { parent::setUp(); // Create a fake mailbox for testing $this->mailbox = new FakeMailbox( config: ['host' => 'imap.example.com', 'port' => 993], folders: [ new FakeFolder( path: 'inbox', messages: [ new FakeMessage( uid: 1, flags: ['\Seen'], contents: 'From: sender@example.com\r\nTo: recipient@example.com\r\nSubject: Test Email\r\n\r\nThis is a test email.' ) ] ) ] ); } public function testProcessNewEmails(): void { // Get the inbox folder $inbox = $this->mailbox->inbox(); // Get all messages $messages = $inbox->messages()->get(); // Assert we have one message $this->assertCount(1, $messages); // Assert the message has the correct subject $this->assertEquals('Test Email', $messages->first()->subject()); // Test your email processing logic here... } } ``` -------------------------------- ### Work with IMAP Subfolders Source: https://imapengine.com/docs/usage/folders Retrieve subfolders of a given folder using the `folders()->get()` method with a wildcard pattern, or find a specific subfolder using `folders()->find()` with its full path. ```php // Get a specific subfolder. $subfolder = $mailbox->folders()->find('Parent/Child'); // List all subfolders within a parent. $subfolders = $mailbox->folders()->get('Parent/*'); ``` -------------------------------- ### Fetch Email Body Structure Source: https://imapengine.com/docs/usage/messages Fetch the body structure for messages using `withBodyStructure()`. This method should be called before `get()` to include structure information in the fetched messages. ```php $messages = $inbox->messages() ->withBodyStructure() ->get(); foreach ($messages as $message) { if ($message->hasBodyStructure()) { $structure = $message->bodyStructure(); } } ``` -------------------------------- ### Retrieve IMAP Folders Source: https://imapengine.com/docs/usage/folders Use the `folders()->get()` method to retrieve all folders or folders matching a glob pattern. Ensure the Mailbox instance is properly configured. ```php use DirectoryTree\ImapEngine\Mailbox; $mailbox = new Mailbox([ // ... ]); // Get all folders. $folders = $mailbox->folders()->get(); // Get folders matching a glob pattern. $folders = $mailbox->folders()->get('*/Subfolder'); ``` -------------------------------- ### Retrieve Raw Message Header Source: https://imapengine.com/docs/usage/messages Get the raw message header as a string using the `head()` method. Returns `null` if the header is not available. ```php $message->head(): string|null ``` -------------------------------- ### Retrieve Raw Message Body Source: https://imapengine.com/docs/usage/messages Get the raw message body as a string using the `body()` method. Returns `null` if the body is not available. ```php $message->body(): string|null ``` -------------------------------- ### Get Encoding and Size of Individual Part Source: https://imapengine.com/docs/usage/messages Retrieve the content encoding (e.g., 'quoted-printable') and size in bytes of an individual message part using the `encoding()` and `size()` methods. ```php $part = $structure->text(); // Get encoding and size $part->encoding(); // "quoted-printable" $part->size(); // 1024 (bytes) ``` -------------------------------- ### Get HTML or Plain Text Version of Message Source: https://imapengine.com/docs/usage/messages Retrieve the HTML or plain text version of an email message if available. This is useful for displaying content in a user-friendly format. ```php // Get the HTML version if available if ($htmlPart = $structure->html()) { $htmlContent = $message->bodyPart($htmlPart->partNumber()); } ``` ```php // Get the plain text version if available if ($textPart = $structure->text()) { $textContent = $message->bodyPart($textPart->partNumber()); } ``` -------------------------------- ### Connect with STARTTLS Source: https://imapengine.com/docs/usage/configuration Establish a connection using STARTTLS encryption on port 143. ```php use DirectoryTree\ImapEngine\Mailbox; $mailbox = new Mailbox([ 'port' => 143, 'encryption' => 'starttls', 'username' => 'your-username', 'password' => 'your-password', 'host' => 'imap.example.com', ]); ``` -------------------------------- ### Creating Folders Source: https://imapengine.com/docs/usage/folders Instructions on how to create new folders, including nested folders, using the `create()` method. ```APIDOC ## Creating Folders ### Description You may create a new folder using the `create()` method. To create a nested folder, separate the parent and child folder names with your IMAP server’s folder delimiter. ### Method `create(string $name)` ### Endpoint N/A (Method on FolderRepository instance) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php // Create a top-level folder. $folder = $mailbox->folders()->create('Archive'); // Create a nested folder. $nestedFolder = $mailbox->folders()->create('Parent/Child'); ``` ### Response #### Success Response (200) - **folder** (Folder) - An instance of the Folder class representing the newly created folder. #### Response Example (Returns a Folder instance) ``` -------------------------------- ### Retrieve Message UID Source: https://imapengine.com/docs/usage/messages Get the unique identifier (UID) of a `Message` object using the `uid()` method. ```php $message->uid(): int ``` -------------------------------- ### Start Polling for New Messages Source: https://imapengine.com/docs/usage/monitoring Initiates the Long Polling method to periodically check for new messages. This method is blocking and should be run in a background process. The frequency parameter controls how often the server is checked. ```php use DirectoryTree\ImapEngine\Message; // Get the inbox folder $inbox = $mailbox->inbox(); // Begin polling the inbox folder every 60 seconds. $inbox->poll(function (Message $message) { // Do something with the newly received message }); ``` -------------------------------- ### Initialize FakeFolder with Messages Source: https://imapengine.com/docs/laravel/usage When creating a `FakeFolder`, you can directly provide an array of `FakeMessage` objects using the `messages` parameter for initial population. ```php use DirectoryTree\ImapEngine\Testing\FakeFolder; use DirectoryTree\ImapEngine\Testing\FakeMessage; $inbox = new FakeFolder( path: 'inbox', flags: ['\Inbox'], messages: [ new FakeMessage(1, ['\Seen'], 'Message content'), new FakeMessage(2, ['\Flagged'], 'Another message content'), ], ); ``` -------------------------------- ### Build a Custom Mailbox Instance Source: https://imapengine.com/docs/laravel/usage Construct a custom mailbox instance by providing its configuration details directly to the `Imap::build` method. ```php use DirectoryTree\ImapEngine\Laravel\Facades\Imap; $mailbox = Imap::build([ 'host' => 'imap.example.com', 'port' => 993, 'username' => 'username', 'password' => 'password', 'encryption' => 'ssl', ]); ``` -------------------------------- ### Create a Fake Mailbox for Testing Source: https://imapengine.com/docs/usage/testing Instantiate `FakeMailbox` to create a mock IMAP mailbox. You can configure its host, port, credentials, and pre-populate it with fake folders and capabilities. ```php use DirectoryTree\ImapEngine\Testing\FakeFolder; use DirectoryTree\ImapEngine\Testing\FakeMailbox; use DirectoryTree\ImapEngine\Testing\FakeMessage; // Create a fake mailbox with configuration $mailbox = new FakeMailbox( // Configuration config: [ 'host' => 'imap.example.com', 'port' => 993, 'username' => 'test@example.com', 'password' => 'password', 'encryption' => 'ssl', ], // Folders folders: [ new FakeFolder('inbox'), new FakeFolder('sent'), new FakeFolder('trash'), ], // Capabilities capabilities: ['IMAP4rev1', 'IDLE', 'UIDPLUS'] ); ``` -------------------------------- ### Retrieve Message Flags Source: https://imapengine.com/docs/usage/messages Get an array of flags currently set on a `Message` object using the `flags()` method. ```php $message->flags(): array ``` -------------------------------- ### Publish ImapEngine Configuration Source: https://imapengine.com/docs/laravel/installation Publish the package's configuration file using the vendor:publish Artisan command. This creates a config/imap.php file. ```bash php artisan vendor:publish --provider=DirectoryTree\ImapEngine\Laravel\ImapServiceProvider ``` -------------------------------- ### Configure IMAP via Environment Variables Source: https://imapengine.com/docs/laravel/installation If your application uses only one IMAP mailbox, configure its details directly in your .env file for simplicity. ```dotenv IMAP_HOST=imap.example.com IMAP_PORT=993 IMAP_USERNAME=your-username IMAP_PASSWORD=your-password IMAP_ENCRYPTION=ssl ``` -------------------------------- ### Use RayLogger for Debugging Source: https://imapengine.com/docs/usage/configuration Integrate Spatie Ray for debugging by setting the 'debug' option to the RayLogger class name. ```php use DirectoryTree\ImapEngine\Mailbox; use DirectoryTree\ImapEngine\Connection\Loggers\RayLogger; $mailbox = new Mailbox([ // ... 'debug' => RayLogger::class, ]); ``` -------------------------------- ### Get Multipart Message Subtype Source: https://imapengine.com/docs/usage/messages Access the subtype of a multipart message, such as 'mixed', 'alternative', or 'related', using the `subtype()` method. ```php $structure = $message->bodyStructure(); // Get the multipart subtype (e.g., "mixed", "alternative", "related") $structure->subtype(); // "alternative" ``` -------------------------------- ### Retrieve Message Subject Source: https://imapengine.com/docs/usage/messages Get the subject of a `Message` object using the `subject()` method. Returns `null` if the subject is not available. ```php $message->subject(): string|null ``` -------------------------------- ### Get Attachment Count Source: https://imapengine.com/docs/usage/messages Retrieve the total number of attachments in a message using the `attachmentCount()` method. This is useful when `hasAttachments()` returns true. ```php // Get attachment count $count = $structure->attachmentCount(); ``` -------------------------------- ### Get Multipart Message Boundary Source: https://imapengine.com/docs/usage/messages Retrieve the boundary parameter for a multipart message, which is used to delimit parts, using the `boundary()` method. ```php $structure = $message->bodyStructure(); // Get the boundary parameter $structure->boundary(); // "Aq14h3UL" ``` -------------------------------- ### Test EmailService with fake mailbox using Pest Source: https://imapengine.com/docs/usage/testing Demonstrates testing the EmailService with a fake mailbox implementation using Pest. ```php it('retrieves messages from the service', function () { // Create a fake mailbox $mailbox = new FakeMailbox( folders: [ new FakeFolder( path: 'inbox', messages: [ new FakeMessage(1, ['\Seen'], 'From: sender1@example.com\r\nSubject: Read Email\r\n\r\nRead email.'), new FakeMessage(2, [], 'From: sender2@example.com\r\nSubject: Unread Email\r\n\r\nUnread email.'), ] ) ] ); // Create the service with the fake mailbox $service = new EmailService($mailbox); // Test the method $messages = $service->messages(); // Assert we get both messages expect($messages)->toHaveCount(2); }); ``` -------------------------------- ### Get Multipart Message Content Type Source: https://imapengine.com/docs/usage/messages Retrieve the content type of a multipart message, like 'multipart/alternative', using the `contentType()` method. ```php $structure = $message->bodyStructure(); // Get the content type $structure->contentType(); // "multipart/alternative" ``` -------------------------------- ### Folder Properties Source: https://imapengine.com/docs/usage/folders How to access properties of a Folder instance such as name, path, and delimiter. ```APIDOC ## Folder Properties ### Description Once you have a `Folder` instance, you may retrieve various properties like its name, full path, and the server's folder delimiter. ### Method `name()`, `path()`, `delimiter()` ### Endpoint N/A (Methods on Folder instance) ### Parameters None ### Request Example ```php $folder = $mailbox->folders()->find('Inbox'); // Get the root folder name (excluding parent folders, e.g. "Inbox"). $name = $folder->name(); // Get the full folder path (e.g. "Inbox/Archive"). $path = $folder->path(); // Get the folder delimiter (e.g. "/"). $delimiter = $folder->delimiter(); ``` ### Response #### Success Response (200) - **name** (string) - The name of the folder. - **path** (string) - The full path of the folder. - **delimiter** (string) - The folder delimiter used by the IMAP server. #### Response Example ```json { "name": "Inbox", "path": "Inbox", "delimiter": "/" } ``` ``` -------------------------------- ### Create Folders Test with Pest Source: https://imapengine.com/docs/usage/testing This Pest test verifies the folder creation functionality. It demonstrates creating a folder, asserting its presence in the mailbox, and adding a message to the newly created folder. ```php it('creates folders', function () { // Create a new folder $folder = $this->mailbox->folders()->create('Archive'); // Assert the folder was created expect($this->mailbox->folders()->find('Archive'))->not->toBeNull(); // Add a message to the new folder $folder->addMessage( new FakeMessage( uid: 1, flags: [], contents: 'From: sender@example.com\r\nSubject: Archived Email\r\n\r\nThis is an archived email.' ) ); // Assert the message was added expect($folder->messages()->get())->toHaveCount(1); }); ``` -------------------------------- ### Get Individual Part Number Source: https://imapengine.com/docs/usage/messages Retrieve the part number (e.g., '1', '1.2', '2.1.3') for a specific `BodyStructurePart` using the `partNumber()` method. ```php $part = $structure->text(); // Get the part number (e.g., "1", "1.2", "2.1.3") $part->partNumber(); // "1" ``` -------------------------------- ### Deleting Folders Source: https://imapengine.com/docs/usage/folders Instructions for deleting a folder using the `delete()` method on a Folder instance. ```APIDOC ## Deleting Folders ### Description To delete a folder, call the `delete()` method on the `Folder` instance. ### Method `delete()` ### Endpoint N/A (Method on Folder instance) ### Parameters None ### Request Example ```php $folder = $mailbox->folders()->find('Archive'); $folder->delete(); ``` ### Response #### Success Response (200) No specific return value, operation is performed. #### Response Example N/A ``` -------------------------------- ### Test EmailService with fake mailbox using PHPUnit Source: https://imapengine.com/docs/usage/testing Demonstrates testing the EmailService with a fake mailbox implementation using PHPUnit. ```php class EmailServiceTest extends TestCase { public function testMessages(): void { // Create a fake mailbox $mailbox = new FakeMailbox( folders: [ new FakeFolder( path: 'inbox', messages: [ new FakeMessage(1, ['\Seen'], 'From: sender1@example.com\r\nSubject: Read Email\r\n\r\nRead email.'), new FakeMessage(2, [], 'From: sender2@example.com\r\nSubject: Unread Email\r\n\r\nUnread email.'), ] ) ] ); // Create the service with the fake mailbox $service = new EmailService($mailbox); // Test the method $messages = $service->messages(); // Assert we get both messages $this->assertCount(2, $messages); } } ``` -------------------------------- ### Retrieve Message ID Source: https://imapengine.com/docs/usage/messages Get the Message-ID header, a globally unique identifier for the message, using the `messageId()` method. Returns `null` if not available. ```php $message->messageId(): ?string|null ``` -------------------------------- ### Retrieve Message Date Source: https://imapengine.com/docs/usage/messages Get the message's date as a Carbon instance using the `date()` method. Returns `null` if the date is not available. ```php $message->date(): Carbon|null ``` -------------------------------- ### Retrieve Specific Header Source: https://imapengine.com/docs/usage/messages Get a specific header from a `Message` object by its name using the `header()` method. Returns `null` if the header is not found. ```php $message->header($name): IHeader|null ``` -------------------------------- ### Instantiate Mbox and Retrieve Messages Source: https://imapengine.com/docs/usage/mbox Instantiate the Mbox class with the path to your Mbox file and iterate over its messages. This method processes the file message-by-message, avoiding high memory usage. ```php use DirectoryTree\ImapEngine\Mbox; $mbox = new Mbox('/home/username/mail/stevebauman.mbox'); /** @var \DirectoryTree\ImapEngine\FileMessage $message */ foreach ($mbox->messages() as $message) { // Work with each FileMessage instance. } ``` -------------------------------- ### On-Demand Fetching Source: https://imapengine.com/docs/usage/messages Demonstrates how to fetch message data on-demand when it's not already loaded, improving efficiency. ```APIDOC ## On-Demand Fetching By default, accessor methods like `subject()`, `from()`, `text()`, and others require the message data to already be loaded (via `withHeaders()`, `withBody()`, etc. on the query). If you want to fetch the required data on-demand when it's not already loaded, you can pass `fetch: true` to these methods: ```php // Fetch headers on-demand if not already loaded $to = $message->to(fetch: true); $from = $message->from(fetch: true); $date = $message->date(fetch: true); $subject = $message->subject(fetch: true); // Fetch body content on-demand if not already loaded $text = $message->text(fetch: true); $html = $message->html(fetch: true); // Fetch attachments using body structure (efficient) $attachments = $message->attachments(fetch: true); ``` ### How It Works When you pass `fetch: true`: * For header methods (`subject`, `from`, `date`, etc.): The message headers are fetched from the server if not already loaded. * For body methods (`text`, `html`): The body structure is used to efficiently fetch only the required part. * For `attachments`: The body structure is used to create lazy-loading attachment streams that fetch content only when accessed. After the first fetch, subsequent calls with `fetch: true` will use the cached data. This is particularly useful when you have a message instance but haven't preloaded any of the message's data: ```php // Find a message without its data $message = $inbox->messages()->find($uid); // Fetch what you need on-demand $from = $message->from(fetch: true); $subject = $message->subject(fetch: true); $attachments = $message->attachments(fetch: true); ``` ``` -------------------------------- ### Fake a Default Mailbox and Add Messages Source: https://imapengine.com/docs/laravel/usage Use `Imap::fake` to create a test mailbox. You can specify mailbox name, configuration, and initial folders. Fake messages can be added to folders after creation. ```php use DirectoryTree\ImapEngine\Testing\FakeFolder; use DirectoryTree\ImapEngine\Testing\FakeMailbox; use DirectoryTree\ImapEngine\Laravel\Facades\Imap; // Fake the default mailbox $mailbox = Imap::fake( mailbox: 'default', config: ['host' => 'imap.example.com', ...], folders: [new FakeFolder('inbox'), new FakeFolder('sent')], ); $inbox = $mailbox->inbox(); // Add a fake message to the folder $inbox->addMessage( new FakeMessage( uid: 1, flags: ['\Seen'], contents: 'Hello, world.', ) ); // Assert that the message is present $this->get(route('mailbox.messages.index', [ 'mailbox' => 'default', 'folder' => 'inbox', ]))->assertSee('Hello, world.'); ``` -------------------------------- ### Renaming / Moving Folders Source: https://imapengine.com/docs/usage/folders How to rename or move a folder using the `move()` method on a Folder instance. ```APIDOC ## Renaming / Moving Folders ### Description To rename a folder, use the `move()` method on the `Folder` instance. This method can also be used to move a folder to a different parent. ### Method `move(string $newNameOrPath)` ### Endpoint N/A (Method on Folder instance) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php $folder = $mailbox->folders()->find('OldName'); $folder->move('NewName'); // To move to a different parent folder: $folder->move('NewParent/NewName'); ``` ### Response #### Success Response (200) No specific return value, operation is performed. #### Response Example N/A ``` -------------------------------- ### Create Folders Test with PHPUnit Source: https://imapengine.com/docs/usage/testing Test folder creation and message addition within a fake mailbox using PHPUnit. This snippet shows how to create a new folder, assert its existence, and add a message to it. ```php public function testCreatingFolders(): void { // Create a new folder $folder = $this->mailbox->folders()->create('Archive'); // Assert the folder was created $this->assertNotNull($this->mailbox->folders()->find('Archive')); // Add a message to the new folder $folder->addMessage( new FakeMessage( uid: 1, flags: [], contents: 'From: sender@example.com\r\nSubject: Archived Email\r\n\r\nThis is an archived email.' ) ); // Assert the message was added $this->assertCount(1, $folder->messages()->get()); } ``` -------------------------------- ### Get Specific Parameter from Individual Part Source: https://imapengine.com/docs/usage/messages Retrieve a specific parameter value (e.g., 'charset') from an individual message part using the `parameter()` method. ```php $part = $structure->text(); // Get a specific parameter $part->parameter('charset'); // "utf-8" ``` -------------------------------- ### Get Text/HTML Part of a Message Source: https://imapengine.com/docs/usage/messages Easily retrieve the text/html part of a message using the `html()` method. Returns null if no HTML part is found. ```php $htmlPart = $structure->html(); ``` -------------------------------- ### Enable Debugging with FileLogger Source: https://imapengine.com/docs/usage/configuration Direct debug messages to a specified log file by setting the 'debug' option to a file path. ```php use DirectoryTree\ImapEngine\Mailbox; // Output debug messages to a file. $mailbox = new Mailbox([ // ... 'debug' => '/path/to/log/file.log', ]); ``` -------------------------------- ### Get All Attachment Parts Source: https://imapengine.com/docs/usage/messages Retrieve an array of all attachment parts within a message using the `attachments()` method. Each element in the array is a `BodyStructurePart` object representing an attachment. ```php $attachments = $structure->attachments(); ``` -------------------------------- ### Connect with OAuth Token Source: https://imapengine.com/docs/usage/configuration Configure the Mailbox for OAuth authentication by providing the token as the password and setting the authentication method. ```php use DirectoryTree\ImapEngine\Mailbox; $token = 'your-oauth-token'; $mailbox = new Mailbox([ 'port' => 993, 'username' => 'your-username', 'password' => $token, 'encryption' => 'ssl', 'authentication' => 'oauth', 'host' => 'imap.example.com', ]); ``` -------------------------------- ### Get Individual Part Content Type Source: https://imapengine.com/docs/usage/messages Retrieve the full content type string (e.g., 'text/plain') for an individual message part using the `contentType()` method. ```php $part = $structure->text(); // Get the content type $part->contentType(); // "text/plain" ``` -------------------------------- ### Get Text/Plain Part of a Message Source: https://imapengine.com/docs/usage/messages Conveniently access the text/plain part of a message using the `text()` method. Returns null if no plain text part is found. ```php $textPart = $structure->text(); ``` -------------------------------- ### Create IMAP Folder Source: https://imapengine.com/docs/usage/folders Create a new IMAP folder using the `folders()->create()` method. For nested folders, use the server's folder delimiter (usually '/') to separate parent and child names. ```php $folder = $mailbox->folders()->create('Archive'); ``` ```php $nestedFolder = $mailbox->folders()->create('Parent/Child'); ``` -------------------------------- ### On-Demand Fetching After Finding Message Source: https://imapengine.com/docs/usage/messages Demonstrates fetching message details like 'from', 'subject', and 'attachments' on-demand after finding a message instance without its data preloaded. Subsequent calls with `fetch: true` will use cached data. ```php $message = $inbox->messages()->find($uid); $from = $message->from(fetch: true); $subject = $message->subject(fetch: true); $attachments = $message->attachments(fetch: true); ``` -------------------------------- ### Working with Subfolders Source: https://imapengine.com/docs/usage/folders Retrieve subfolders of a given folder or list all subfolders within a parent folder. ```APIDOC ## Working with Subfolders ### Description You may retrieve subfolders of a folder using the `get()` method on the `FolderRepository` instance, often by using a glob pattern. ### Method `get(string $pattern)` ### Endpoint N/A (Method on FolderRepository instance) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php // Get a specific subfolder by its full path. $subfolder = $mailbox->folders()->find('Parent/Child'); // List all direct subfolders within a parent folder. $subfolders = $mailbox->folders()->get('Parent/*'); ``` ### Response #### Success Response (200) - **subfolders** (array) - An array of Folder instances representing the subfolders. #### Response Example ```json [ { "name": "Child1", "path": "Parent/Child1", "delimiter": "/" }, { "name": "Child2", "path": "Parent/Child2", "delimiter": "/" } ] ``` ``` -------------------------------- ### Fetch Headers On-Demand Source: https://imapengine.com/docs/usage/messages Fetch message headers like 'to', 'from', and 'date' on-demand if they are not already loaded. Subsequent calls with `fetch: true` will use cached data. ```php $to = $message->to(fetch: true); $from = $message->from(fetch: true); $date = $message->date(fetch: true); $subject = $message->subject(fetch: true); ``` -------------------------------- ### Flatten All Message Parts Source: https://imapengine.com/docs/usage/messages Get a flattened list of all message parts, including nested parts, using the `flatten()` method. This provides a simple array of all `BodyStructurePart` objects. ```php $allParts = $structure->flatten(); ``` -------------------------------- ### Mark Messages as Read Test with PHPUnit Source: https://imapengine.com/docs/usage/testing Demonstrates how to test marking messages as read using PHPUnit. This involves adding an unread message, asserting its initial state, marking it, and asserting the final state. ```php public function testMarkingMessagesAsRead(): void { // Get the inbox folder $inbox = $this->mailbox->inbox(); // Add a new unread message $inbox->addMessage( new FakeMessage( uid: 2, flags: [], // No flags means unread contents: 'From: sender@example.com\r\nSubject: Unread Email\r\n\r\nThis is an unread email.' ) ); // Get the unread message $message = $inbox->messages()->find(2); // Assert it's not seen $this->assertFalse($message->isSeen()); // Mark it as seen $message->markSeen(); // Assert it's now seen $this->assertTrue($message->isSeen()); } ``` -------------------------------- ### Get Attachment Metadata Source: https://imapengine.com/docs/usage/messages Access metadata for each attachment, including filename, content type, size in bytes, and encoding, using methods like `filename()`, `contentType()`, `size()`, and `encoding()`. ```php foreach ($attachments as $attachment) { // Get attachment metadata $attachment->filename(); // "document.pdf" $attachment->contentType(); // "application/pdf" $attachment->size(); // 50000 (bytes) $attachment->encoding(); // "base64" ``` -------------------------------- ### Fetch Full Message Content with IDLE Source: https://imapengine.com/docs/usage/monitoring Configures the IDLE method to fetch full message content, including body, headers, and attachments, by adjusting the MessageQuery. You must return the MessageQuery instance from the callback. ```php use DirectoryTree\ImapEngine\MessageQuery; $inbox->idle(function (Message $message) { // Handle new message... }, function (MessageQuery $query) { // Adjust the query to fetch all message content... return $query->withBody() ->withHeaders() ->withFlags(); }); ``` -------------------------------- ### Swap Mailbox Instance Source: https://imapengine.com/docs/laravel/usage Replace an existing mailbox instance in the container with a custom one using `Imap::swap`. This is useful for dependency injection testing. ```php use DirectoryTree\ImapEngine\Laravel\Facades\Imap; use DirectoryTree\ImapEngine\Mailbox; $customMailbox = new Mailbox([ // Custom configuration ]); Imap::swap('default', $customMailbox); ``` -------------------------------- ### Load Additional Message Data with Watch Command - Artisan Source: https://imapengine.com/docs/laravel/usage Specify additional message data to be loaded when monitoring mailboxes with the `imap:watch` command. Options include flags, headers, and body. ```bash php artisan imap:watch default --with=flags,headers,body ``` -------------------------------- ### Get Specific IMAP Folder Source: https://imapengine.com/docs/usage/folders Retrieve a specific folder by name using `folders()->find()` or `folders()->findOrFail()`. The `inbox()` method provides a shortcut for the mandatory INBOX folder. ```php // Get the inbox folder. $inbox = $mailbox->inbox(); // Find a specific folder by name. $folder = $mailbox->folders()->find('Sent'); // Find a folder or fail (throw an exception). $folder = $mailbox->folders()->findOrFail('Important'); ``` -------------------------------- ### Stop IMAP Polling with a Closure Source: https://imapengine.com/docs/usage/monitoring To stop polling, return `false` from the frequency parameter using a closure. This example demonstrates stopping the poll after a message with the subject 'Stop' is processed. ```php $shouldContinue = true; $inbox->poll( function (Message $message) use (&$shouldContinue) { // Process message... // Stop polling after processing a specific message if ($message->subject() === 'Stop') { $shouldContinue = false; } }, frequency: function () use (&$shouldContinue) { return $shouldContinue ? 60 : false; } ); ``` -------------------------------- ### Checking Folder Capabilities Source: https://imapengine.com/docs/usage/folders Inspect the IMAP capabilities advertised by the server for the current folder, such as IDLE, MOVE, or QUOTA. ```APIDOC ## Checking Folder Capabilities ### Description To inspect the IMAP capabilities advertised while working with a folder, call `capabilities()`. This method proxies to the mailbox's capability list, letting you verify support for features like `IDLE`, `MOVE`, or `QUOTA`. ### Method `capabilities()` ### Endpoint N/A (Method on Folder instance) ### Parameters None ### Request Example ```php $folder = $mailbox->folders()->find('Inbox'); $capabilities = $folder->capabilities(); // array if (in_array('IDLE', $capabilities, strict: true)) { // Server supports IDLE for this mailbox. } ``` ### Response #### Success Response (200) - **capabilities** (array) - An array of strings representing the supported IMAP capabilities. #### Response Example ```json [ "IMAP4rev1", "IDLE", "NAMESPACE", "QUOTA", "MOVE" ] ``` ``` -------------------------------- ### Get Attachment Disposition Information Source: https://imapengine.com/docs/usage/messages Inspect the content disposition of an attachment to determine if it's an attachment or inline, and access its parameters like filename using the `disposition()` method and its associated properties. ```php $disposition = $attachment->disposition(); $disposition->type(); // ContentDispositionType::Attachment $disposition->isAttachment(); // true $disposition->isInline(); // false $disposition->parameters(); // ['filename' => 'document.pdf'] ``` -------------------------------- ### Get Individual Part MIME Type and Subtype Source: https://imapengine.com/docs/usage/messages Extract the MIME type (e.g., 'text') and subtype (e.g., 'plain') of an individual message part using the `type()` and `subtype()` methods. ```php $part = $structure->text(); // Get the MIME type and subtype $part->type(); // "text" $part->subtype(); // "plain" ``` -------------------------------- ### Connect to Mailbox Manually Source: https://imapengine.com/docs/usage/connecting Manually connect to the mailbox using the `connect` method. This method can throw `ImapConnectionException` for connection issues or `ImapCommandException` for authentication failures. Import necessary exception classes. ```php use DirectoryTree\ImapEngine\Mailbox; use DirectoryTree\ImapEngine\Exceptions\ImapCommandException; use DirectoryTree\ImapEngine\Exceptions\ImapConnectionException; $mailbox = new Mailbox([ // ... ]); try { $mailbox->connect(); } catch (ImapCommandException $e) { // Handle authentication failures (invalid credentials). } catch (ImapConnectionException $e) { // Handle connection failures (network, server issues). } ``` -------------------------------- ### Get Direct Child Parts of a Multipart Message Source: https://imapengine.com/docs/usage/messages Retrieve the direct child parts of a multipart message, which can be individual `BodyStructurePart` objects or nested `BodyStructureCollection` objects, using the `parts()` method. ```php $structure = $message->bodyStructure(); // Get direct child parts $structure->parts(); // Array of BodyStructurePart or BodyStructureCollection ``` -------------------------------- ### Mark Message as Seen Source: https://imapengine.com/docs/usage/messages Marks the current message as read. This operation directly corresponds to the IMAP `STORE` command. ```php $message->markSeen(): void ``` -------------------------------- ### Add Fake Messages to Folders Source: https://imapengine.com/docs/usage/testing Messages can be added to a `FakeFolder` either during its initialization or after its creation using the `addMessage` method. Each message requires a UID, flags, and its raw contents. ```php // Add messages during folder initialization $inbox = new FakeFolder( path: 'inbox', flags: ['\Inbox'], messages: [ new FakeMessage(1, ['\Seen'], 'From: sender@example.com\r\nTo: recipient@example.com\r\nSubject: Test Email\r\n\r\nThis is a test email.'), new FakeMessage(2, ['\Flagged'], 'From: another@example.com\r\nTo: recipient@example.com\r\nSubject: Important Email\r\n\r\nThis is an important email.'), ] ); ``` ```php // Or add messages after folder creation $inbox = new FakeFolder('inbox'); $inbox->addMessage( new FakeMessage( uid: 1, flags: ['\Seen'], contents: 'From: sender@example.com\r\nTo: recipient@example.com\r\nSubject: Test Email\r\n\r\nThis is a test email.' ) ); ``` -------------------------------- ### Check IMAP Folder Capabilities Source: https://imapengine.com/docs/usage/folders Inspect the IMAP capabilities advertised by the server for a folder using the `capabilities()` method. This allows checking for support of features like IDLE, MOVE, or QUOTA. ```php $capabilities = $folder->capabilities(); // array if (in_array('IDLE', $capabilities, strict: true)) { // Server supports IDLE for this mailbox. } ``` -------------------------------- ### Connect with Unencrypted Connection Source: https://imapengine.com/docs/usage/configuration Configure the Mailbox for an unencrypted connection by setting encryption to null and using the standard unencrypted port. ```php use DirectoryTree\ImapEngine\Mailbox; $mailbox = new Mailbox([ 'port' => 143, 'encryption' => null, 'username' => 'your-username', 'password' => 'your-password', 'host' => 'imap.example.com', ]); ``` -------------------------------- ### Access FileMessage Content Source: https://imapengine.com/docs/usage/mbox Interact with FileMessage instances to retrieve raw message content, check for a body, get headers, and process attachments. Note that the uid() method is not available for FileMessage instances. ```php /** @var \DirectoryTree\ImapEngine\FileMessage $message */ foreach ($mbox->messages() as $message) { // Get the raw contents of the message: $raw = $message->raw(); // Check if the message has a body: if ($message->hasBody()) { // Retrieve the message body. $body = $message->body(); } // Retrieve headers (if available): $headers = $message->headers(); // Retrieve attachments: foreach ($message->attachments() as $attachment) { // Work with each attachment. $attachmentContents = $attachment->contents(); } } ``` -------------------------------- ### Select IMAP Folder Source: https://imapengine.com/docs/usage/folders Explicitly select an IMAP folder on the server using the `select()` method on the `Folder` instance. This is often done automatically by ImapEngine but can be forced. ```php $folder->select(); // Or force re-selection $folder->select(true); ``` -------------------------------- ### Combine Sorting with Search Criteria Source: https://imapengine.com/docs/usage/messages Integrate server-side sorting with search criteria like `unseen()` or `from()` to retrieve and order specific message sets efficiently. ```php // Get unread messages sorted by arrival time (newest first) $messages = $inbox->messages() ->unseen() ->sortByDesc('arrival') ->get(); // Get messages from a sender sorted by subject $messages = $inbox->messages() ->from('newsletter@example.com') ->sortBy('subject') ->get(); ``` -------------------------------- ### Connect to Mailbox Automatically Source: https://imapengine.com/docs/usage/connecting The ImapEngine automatically connects to the mailbox when a method requiring connectivity is called. Ensure you have the Mailbox class imported. ```php use DirectoryTree\ImapEngine\Mailbox; $mailbox = new Mailbox([ // ... ]); // Automatically connects to the mailbox. $folders = $mailbox->folders()->get(); ``` -------------------------------- ### Manage Mailbox Configuration Source: https://imapengine.com/docs/usage/connecting Retrieve the entire mailbox configuration array or specific configuration values using the `config()` method. Use dot-notation for nested values. ```php // Get the entire config. $config = $mailbox->config(); // Get a specific config value with a default. $port = $mailbox->config('port', 993); ``` ```php $proxyUsername = $mailbox->config('proxy.username'); ```