### Install Decoding Modules
Source: https://github.com/webklex/php-imap/wiki/Installation
Install mbstring and mcrypt modules for PHP. Reload Apache after installation.
```shell
sudo apt-get install php*-mbstring php*-mcrypt && sudo apache2ctl graceful
```
--------------------------------
### Basic IMAP Usage Example
Source: https://github.com/webklex/php-imap/blob/master/README.md
This example demonstrates how to connect to an IMAP server, retrieve all mailboxes, iterate through messages in each mailbox, display message subjects and attachments, and move messages to a specified folder. Ensure you have a valid configuration file and account identifier.
```php
use Webklex\PHPIMAP\ClientManager;
require_once "vendor/autoload.php";
$cm = new ClientManager('path/to/config/imap.php');
/** @var \Webklex\PHPIMAP\Client $client */
$client = $cm->account('account_identifier');
//Connect to the IMAP Server
$client->connect();
//Get all Mailboxes
/** @var \Webklex\PHPIMAP\Support\FolderCollection $folders */
$folders = $client->getFolders();
//Loop through every Mailbox
/** @var \Webklex\PHPIMAP\Folder $folder */
foreach($folders as $folder){
//Get all Messages of the current Mailbox $folder
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->messages()->all()->get();
/** @var \Webklex\PHPIMAP\Message $message */
foreach($messages as $message){
echo $message->getSubject().'
';
echo 'Attachments: '.$message->getAttachments()->count().'
';
echo $message->getHTMLBody();
//Move the current Message to 'INBOX.read'
if($message->move('INBOX.read') == true){
echo 'Message has been moved';
}else{
echo 'Message could not be moved';
}
}
}
```
--------------------------------
### Install PHP-IMAP Module (Optional)
Source: https://github.com/webklex/php-imap/wiki/Installation
Install the php-imap module if you encounter encoding issues. Reload Apache after installation.
```shell
sudo apt-get install php*-imap && sudo apache2ctl graceful
```
--------------------------------
### Install PHP-IMAP via Composer
Source: https://context7.com/webklex/php-imap/llms.txt
Install the PHP-IMAP package using Composer. Ensure necessary decoding modules are installed first.
```bash
# Install required decoding modules
sudo apt-get install php*-mbstring php*-mcrypt && sudo apache2ctl graceful
# (Optional) Install php-imap module for better encoding support
sudo apt-get install php*-imap && sudo apache2ctl graceful
# Install PHP-IMAP via Composer
composer require webklex/php-imap
```
--------------------------------
### Install PHP-IMAP Package via Composer
Source: https://github.com/webklex/php-imap/wiki/Installation
Install the webklex/php-imap package using Composer.
```shell
composer require webklex/php-imap
```
--------------------------------
### List and Access Mailboxes with Folder Class
Source: https://context7.com/webklex/php-imap/llms.txt
Retrieve all available mailboxes (folders) and access specific folder properties. This example iterates through folders and demonstrates accessing properties like name, path, and children status.
```php
getFolders();
// Loop through all folders
foreach ($folders as $folder) {
echo "Folder: " . $folder->name . "\n";
echo "Full path: " . $folder->path . "\n";
echo "Has children: " . ($folder->has_children ? 'Yes' : 'No') . "\n";
}
// Get a specific folder by path
/** @var \Webklex\PHPIMAP\Folder $folder */
$folder = $client->getFolder('INBOX');
$sentFolder = $client->getFolder('INBOX.Sent');
$customFolder = $client->getFolder('INBOX.MyFolder');
// Access folder properties
echo "Folder name: " . $folder->name . "\n";
echo "Full name: " . $folder->full_name . "\n";
echo "Delimiter: " . $folder->delimiter . "\n";
echo "Can select: " . (!$folder->no_select ? 'Yes' : 'No') . "\n";
```
--------------------------------
### Implement Custom Message Mask
Source: https://github.com/webklex/php-imap/wiki/Masking
Extend `MessageMask` to create a custom message mask with additional methods. This example shows a `token` method.
```php
/** @var \Webklex\PHPIMAP\Message $oMessage */
class CustomMessageMask extends \Webklex\PHPIMAP\Support\Masks\MessageMask {
/**
* New custom method which can be called through a mask
* @return string
*/
public function token(){
return implode('-', [$this->message_id, $this->uid, $this->message_no]);
}
}
$mask = $oMessage->mask(CustomMessageMask::class);
echo $mask->token().'@'.$mask->uid;
```
--------------------------------
### Limit and Paginate Emails with Since Date
Source: https://github.com/webklex/php-imap/wiki/Result-limiting
Fetch emails for a specific page, starting from a given date. Ensure the folder object is properly initialized.
```php
/** @var \Webklex\PHPIMAP\Folder $oFolder */
//Get all messages for page 2 since march 15 2018 where each page contains 10 messages
/** @var \Webklex\PHPIMAP\Support\MessageCollection $aMessage */
$aMessage = $oFolder->query()->since('15.03.2018')->limit(10, 2)->get();
```
--------------------------------
### Get Specific Folder
Source: https://github.com/webklex/php-imap/wiki/Folder---Mailbox
Fetch a specific folder by its name. The folder name can be a direct name or a path. Ensure the folder exists before attempting to retrieve it.
```php
/** @var \Webklex\PHPIMAP\Client $oClient */
/** @var \Webklex\PHPIMAP\Folder $oFolder */
$oFolder = $oClient->getFolder('INBOX.name');
```
--------------------------------
### Get Specific Folder
Source: https://github.com/webklex/php-imap/wiki/Folder---Mailbox
Retrieves a specific folder by its name.
```APIDOC
## Get a Specific Folder
### Description
Retrieves a specific folder (mailbox) by providing its full name.
### Method
GET (conceptual, as this is a client-side operation)
### Endpoint
N/A (Client-side operation)
### Parameters
#### Path Parameters
- **folder_name** (string) - Required - The full name of the folder to retrieve (e.g., 'INBOX.name').
### Request Example
```php
/** @var \Webklex\PHPIMAP\Client $oClient */
$oFolder = $oClient->getFolder('INBOX.name');
```
### Response
#### Success Response (200)
- **oFolder** (Folder) - A Folder object representing the requested mailbox.
```
--------------------------------
### Get All Messages PHP IMAP
Source: https://github.com/webklex/php-imap/wiki/Search-for-messages
Retrieves all messages from the current folder. Ensure the $oFolder variable is properly initialized.
```php
/** @var \Webklex\PHPIMAP\Folder $oFolder */
//Get all messages
/** @var \Webklex\PHPIMAP\Support\MessageCollection $aMessage */
$aMessage = $oFolder->query()->all()->get();
```
--------------------------------
### Paginate and Get Messages with Custom Options
Source: https://github.com/webklex/php-imap/wiki/Pagination
Fetch messages within a date range and paginate the results with custom page size and name. This method allows for fine-grained control over pagination parameters.
```php
/** @var \Webklex\PHPIMAP\Folder $oFolder */
/** @var \Illuminate\Pagination\LengthAwarePaginator $paginator */
$paginator = $oFolder->search()
->since(\Carbon::now()->subDays(14))->get()
->paginate($perPage = 5, $page = null, $pageName = 'imap_blade_example');
```
--------------------------------
### Format PHP Code in Issues
Source: https://github.com/webklex/php-imap/blob/master/README.md
When reporting issues, format your PHP source code using triple backticks with 'php' specified, as shown in the example. This improves readability.
```php
echo 'your php code...';
```
--------------------------------
### Download and Save Email Attachments
Source: https://context7.com/webklex/php-imap/llms.txt
Iterate through message attachments to get their properties like filename, MIME type, and size. Save attachments to a specified directory, optionally with a custom filename. Content can also be retrieved directly.
```php
getAttachments();
echo "Number of attachments: " . $attachments->count() . "\n";
// Save all attachments to a directory
$attachments->each(function ($attachment) {
/** @var \Webklex\PHPIMAP\Attachment $attachment */
// Get attachment properties
echo "Filename: " . $attachment->getName() . "\n";
echo "MIME Type: " . $attachment->getMimeType() . "\n";
echo "Size: " . $attachment->getSize() . " bytes\n";
// Save attachment to a specific path
$attachment->save("/path/to/attachments/");
// Or save with a custom filename
$attachment->save("/path/to/attachments/", "custom_name.pdf");
});
// Get attachment content directly
foreach ($attachments as $attachment) {
$content = $attachment->getContent();
$base64Content = base64_encode($content);
// Process inline images
if ($attachment->disposition === 'inline') {
$cid = $attachment->id;
echo "Inline attachment CID: $cid\n";
}
}
```
--------------------------------
### Display Paginated IMAP Messages in Blade
Source: https://github.com/webklex/php-imap/wiki/Pagination
Render a table of paginated IMAP messages using Blade templating. This example shows how to iterate through the paginator and display message details, including UID, Subject, From, and Attachments.
```html
| UID |
Subject |
From |
Attachments |
count() > 0): ?>
| getUid(); ?> |
getSubject(); ?> |
getFrom()[0]->mail; ?> |
getAttachments()->count() > 0 ? 'yes' : 'no'; ?> |
| No messages found |
links(); ?>
```
--------------------------------
### Alternative Query Syntaxes
Source: https://context7.com/webklex/php-imap/llms.txt
Demonstrates equivalent ways to construct search queries using different method names. These syntaxes achieve the same search results.
```php
// Alternative query syntaxes (all equivalent)
$messages = $folder->query()->whereText('hello world')->whereSince('15.03.2018')->get();
$messages = $folder->search()->text('hello world')->since('15.03.2018')->get();
$messages = $folder->messages()->text('hello world')->since('15.03.2018')->get();
```
--------------------------------
### Create IMAP Connections with ClientManager
Source: https://context7.com/webklex/php-imap/llms.txt
Demonstrates creating IMAP client connections using different methods: configuration file, programmatic options, Gmail OAuth, and Gmail App Password. Ensure to connect after making the client.
```php
account('default'); // Use account identifier from config
// Method 2: Using an array of options
$cm = new ClientManager($options = []);
$client = $cm->make([
'host' => 'imap.example.com',
'port' => 993,
'encryption' => 'ssl',
'validate_cert' => true,
'username' => 'user@example.com',
'password' => 'your-password',
'protocol' => 'imap'
]);
// Connect to the IMAP server
$client->connect();
// Method 3: Gmail with OAuth authentication
$cm = new ClientManager();
$client = $cm->make([
'host' => 'imap.gmail.com',
'port' => 993,
'encryption' => 'ssl',
'validate_cert' => true,
'username' => 'example@gmail.com',
'password' => 'YOUR-OAUTH-ACCESS-TOKEN',
'authentication' => 'oauth',
'protocol' => 'imap'
]);
$client->connect();
// Method 4: Gmail with App Password
$client = $cm->make([
'host' => 'imap.googlemail.com',
'port' => 993,
'encryption' => 'ssl',
'validate_cert' => false,
'protocol' => 'imap',
'username' => 'username@gmail.com',
'password' => 'app-generated-password'
]);
$client->connect();
```
--------------------------------
### Attachment Mask Operations
Source: https://github.com/webklex/php-imap/wiki/Client::class
Provides methods to get and set the default attachment mask.
```APIDOC
## GET /api/imap/attachment/mask
### Description
Get the current default attachment mask class name.
### Method
GET
### Endpoint
/api/imap/attachment/mask
### Response
#### Success Response (200)
- **mask** (string) - The current default attachment mask class name.
#### Response Example
```json
{
"mask": "DefaultAttachmentMask"
}
```
## POST /api/imap/attachment/mask
### Description
Set the default attachment mask.
### Method
POST
### Endpoint
/api/imap/attachment/mask
### Parameters
#### Request Body
- **mask** (string) - Required - The class name for the default attachment mask.
### Request Example
```json
{
"mask": "NewAttachmentMask"
}
```
### Response
#### Success Response (200)
- **message** (string) - Confirmation message.
#### Response Example
```json
{
"message": "Default attachment mask set successfully."
}
```
```
--------------------------------
### Message Mask Operations
Source: https://github.com/webklex/php-imap/wiki/Client::class
Provides methods to get and set the default message mask.
```APIDOC
## GET /api/imap/message/mask
### Description
Get the current default message mask class name.
### Method
GET
### Endpoint
/api/imap/message/mask
### Response
#### Success Response (200)
- **mask** (string) - The current default message mask class name.
#### Response Example
```json
{
"mask": "DefaultMessageMask"
}
```
## POST /api/imap/message/mask
### Description
Set the default attachment mask.
### Method
POST
### Endpoint
/api/imap/message/mask
### Parameters
#### Request Body
- **mask** (string) - Required - The class name for the default message mask.
### Request Example
```json
{
"mask": "NewMessageMask"
}
```
### Response
#### Success Response (200)
- **message** (string) - Confirmation message.
#### Response Example
```json
{
"message": "Default message mask set successfully."
}
```
```
--------------------------------
### Configure Live Mailbox Testing
Source: https://github.com/webklex/php-imap/blob/master/README.md
Copy and adjust the `phpunit.xml.dist` file to `phpunit.xml` to provide valid IMAP configuration for live mailbox testing. Ensure the test account meets the specified requirements.
```xml
```
--------------------------------
### Get Mask Class Name
Source: https://github.com/webklex/php-imap/wiki/Message::class
Retrieves the current mask class name used by the IMAP library.
```APIDOC
## GET /webklex/php-imap/getMask
### Description
Get the current mask class name.
### Method
GET
### Endpoint
/webklex/php-imap/getMask
### Parameters
None
### Response
#### Success Response (200)
- **maskClassName** (string) - The name of the current mask class.
```
--------------------------------
### Run Composer Tests
Source: https://github.com/webklex/php-imap/blob/master/README.md
Execute this command in your terminal to run the project's tests.
```bash
composer test
```
--------------------------------
### Build Docker Image for IMAP Server
Source: https://github.com/webklex/php-imap/blob/master/README.md
Build the Docker image for the IMAP server by navigating to the Docker directory and running the docker build command. This image is used for testing purposes.
```bash
cd .github/docker
docker build -t php-imap-server .
```
--------------------------------
### Connect and Process Emails with PHP IMAP
Source: https://github.com/webklex/php-imap/wiki/Basic-usage-example
Use this snippet to connect to an IMAP server, fetch all emails from every folder, display their subjects and HTML bodies, and move them to the 'INBOX.read' folder. Ensure you have a valid configuration file or provide options directly.
```php
use Webklex\PHPIMAP\ClientManager;
use Webklex\PHPIMAP\Client;
$cm = new ClientManager('path/to/config/imap.php');
// or use an array of options instead
$cm = new ClientManager($options = []);
/** @var \Webklex\PHPIMAP\Client $client */
$client = $cm->account('account_identifier');
// or create a new instance manually
$client = $cm->make([
'host' => 'somehost.com',
'port' => 993,
'encryption' => 'ssl',
'validate_cert' => true,
'username' => 'username',
'password' => 'password',
'protocol' => 'imap'
]);
//Connect to the IMAP Server
$client->connect();
//Get all Mailboxes
/** @var \Webklex\PHPIMAP\Support\FolderCollection $folders */
$folders = $client->getFolders();
//Loop through every Mailbox
/** @var \Webklex\PHPIMAP\Folder $folder */
foreach($folders as $folder){
//Get all Messages of the current Mailbox $folder
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->messages()->all()->get();
/** @var \Webklex\PHPIMAP\Message $message */
foreach($messages as $message){
echo $message->getSubject().'
';
echo 'Attachments: '.$message->getAttachments()->count().'
';
echo $message->getHTMLBody();
//Move the current Message to 'INBOX.read'
if($message->moveToFolder('INBOX.read') == true){
echo 'Message has ben moved';
}else{
echo 'Message could not be moved';
}
}
}
```
--------------------------------
### Get the Folder Containing the Message
Source: https://context7.com/webklex/php-imap/llms.txt
Retrieves the folder object to which the current message belongs. This can be useful for context or further operations on the message's original folder.
```php
// Get the folder containing the message
$messageFolder = $message->getFolder();
```
--------------------------------
### Complete PHP-IMAP Configuration
Source: https://context7.com/webklex/php-imap/llms.txt
This configuration file defines accounts, fetch options, decoding settings, events, and masks for the IMAP client. It includes settings for date format, default account, security options, multiple account configurations (including Gmail with OAuth), fetch options, decoding options, available flags, event handlers, and default masks.
```php
'd-M-Y',
// Default account identifier
'default' => 'default',
// Security options
'security' => [
'detect_spoofing' => true,
'detect_spoofing_exception' => false,
'sanitize_filenames' => true,
],
// Account configurations
'accounts' => [
'default' => [
'host' => 'imap.example.com',
'port' => 993,
'protocol' => 'imap', // imap, legacy-imap, pop3, nntp
'encryption' => 'ssl', // false, ssl, tls, starttls, notls
'validate_cert' => true,
'username' => 'user@example.com',
'password' => 'password',
'authentication' => null, // null or 'oauth'
'timeout' => 30,
'proxy' => [
'socket' => null,
'request_fulluri' => false,
'username' => null,
'password' => null,
],
],
'gmail' => [
'host' => 'imap.gmail.com',
'port' => 993,
'encryption' => 'ssl',
'validate_cert' => true,
'username' => 'example@gmail.com',
'password' => 'oauth-token-or-app-password',
'authentication' => 'oauth',
],
],
// Fetch options
'options' => [
'delimiter' => '/',
'fetch' => \Webklex\PHPIMAP\IMAP::FT_PEEK, // Don't mark as read
'sequence' => \Webklex\PHPIMAP\IMAP::ST_UID,
'fetch_body' => true,
'fetch_flags' => true,
'soft_fail' => false,
'message_key' => 'list', // id, number, list, uid
'fetch_order' => 'asc', // asc, desc
'dispositions' => ['attachment', 'inline'],
'common_folders' => [
'root' => 'INBOX',
'junk' => 'INBOX/Junk',
'draft' => 'INBOX/Drafts',
'sent' => 'INBOX/Sent',
'trash' => 'INBOX/Trash',
],
],
// Decoding options
'decoding' => [
'options' => [
'header' => 'utf-8',
'message' => 'utf-8',
'attachment' => 'utf-8'
],
],
// Available flags
'flags' => ['recent', 'flagged', 'answered', 'deleted', 'seen', 'draft'],
// Event handlers
'events' => [
'message' => [
'new' => \Webklex\PHPIMAP\Events\MessageNewEvent::class,
'moved' => \Webklex\PHPIMAP\Events\MessageMovedEvent::class,
'copied' => \Webklex\PHPIMAP\Events\MessageCopiedEvent::class,
'deleted' => \Webklex\PHPIMAP\Events\MessageDeletedEvent::class,
'restored' => \Webklex\PHPIMAP\Events\MessageRestoredEvent::class,
],
'folder' => [
'new' => \Webklex\PHPIMAP\Events\FolderNewEvent::class,
'moved' => \Webklex\PHPIMAP\Events\FolderMovedEvent::class,
'deleted' => \Webklex\PHPIMAP\Events\FolderDeletedEvent::class,
],
'flag' => [
'new' => \Webklex\PHPIMAP\Events\FlagNewEvent::class,
'deleted' => \Webklex\PHPIMAP\Events\FlagDeletedEvent::class,
],
],
// Default masks
'masks' => [
'message' => \Webklex\PHPIMAP\Support\Masks\MessageMask::class,
'attachment' => \Webklex\PHPIMAP\Support\Masks\AttachmentMask::class
]
];
```
--------------------------------
### Get Message Body Content
Source: https://context7.com/webklex/php-imap/llms.txt
Retrieves the HTML and plain text versions of the email body. Use these methods to display or process the email content.
```php
// Get message body content
$htmlBody = $message->getHTMLBody();
$textBody = $message->getTextBody();
```
--------------------------------
### Connect using OAuth Token
Source: https://github.com/webklex/php-imap/wiki/Google-Mail---Gmail
Use this method when authenticating with OAuth. Ensure you have obtained an access token beforehand and set the 'authentication' to 'oauth' with the token as the 'password'.
```php
$cm = new \Webklex\PHPIMAP\Clientmanager();
/** @var \Webklex\PHPIMAP\Client $message */
$client = $cm->make([
'host' => 'imap.googlemail.com',
'port' => 993,
'encryption' => 'ssl',
'validate_cert' => false,
'protocol' => 'imap',
'username' => 'username@gmail.com',
'password' => 'ACCESS-TOKEN',
'authentication' => "oauth",
]);
$client->connect();
```
--------------------------------
### Create and Register Custom MessageNewEvent
Source: https://github.com/webklex/php-imap/wiki/Events
Extend the base MessageNewEvent class to create a custom event. Register the custom event using the client's setEvent method. Alternatively, configure custom events in the `events.message.new` section of your configuration file.
```php
class CustomMessageNewEvent extends Webklex\PHPIMAP\Events\MessageNewEvent {
/**
* Create a new event instance.
* @var Message[] $messages
* @return void
*/
public function __construct($messages) {
$this->message = $messages[0];
echo "New message: ".$this->message->subject."\n";
}
}
/** @var \Webklex\PHPIMAP\Client $client */
$client->setEvent("message", "new", CustomMessageNewEvent::class);
```
--------------------------------
### List All Available Folders
Source: https://github.com/webklex/php-imap/wiki/Folder---Mailbox
Retrieve a collection of all available folders in the IMAP account. Ensure the client is authenticated before calling this method.
```php
/** @var \Webklex\PHPIMAP\Client $oClient */
/** @var \Webklex\PHPIMAP\Support\FolderCollection $aFolder */
$aFolder = $oClient->getFolders();
```
--------------------------------
### Using Search Aliases PHP IMAP
Source: https://github.com/webklex/php-imap/wiki/Search-for-messages
Demonstrates the use of aliases 'search()' and 'messages()' which are equivalent to 'query()' for initiating a search operation.
```php
// Folder::search() is just an alias for Folder::query()
/** @var \Webklex\PHPIMAP\Support\MessageCollection $aMessage */
$aMessage = $oFolder->search()->text('hello world')->since('15.03.2018')->get();
```
```php
// Folder::messages() is just an alias for Folder::query()
/** @var \Webklex\PHPIMAP\Support\MessageCollection $aMessage */
$aMessage = $oFolder->messages()->text('hello world')->since('15.03.2018')->get();
```
--------------------------------
### Connect using Application Password
Source: https://github.com/webklex/php-imap/wiki/Google-Mail---Gmail
This snippet demonstrates connecting using a generated application password, typically obtained from Google's security settings for apps that don't support modern sign-in flows. Ensure the password is correct and generated for the 'Mail' app.
```php
$cm = new \Webklex\PHPIMAP\Clientmanager();
/** @var \Webklex\PHPIMAP\Client $message */
$client = $cm->make([
'host' => 'imap.googlemail.com',
'port' => 993,
'encryption' => 'ssl',
'validate_cert' => false,
'protocol' => 'imap',
'username' => 'username@gmail.com',
'password' => 'new-generated-password'
]);
$client->connect();
```
--------------------------------
### Configuration and Connection Management API
Source: https://github.com/webklex/php-imap/wiki/Client::class
API endpoints for managing client configuration and establishing/maintaining IMAP connections.
```APIDOC
## setConfig
### Description
Set the Client configuration. Take a look at `config/imap.php` for more inspiration.
### Method
POST
### Endpoint
/webklex/php-imap/setConfig
### Parameters
#### Request Body
- **config** (array) - Required - Client configuration array.
### Request Example
```json
{
"config": {
"host": "imap.example.com",
"username": "user@example.com",
"password": "password"
}
}
```
### Response
#### Success Response (200)
- **self** (object) - Returns the client instance for chaining.
#### Response Example
```json
{
"self": "[Client Instance]"
}
```
```
```APIDOC
## getConnection
### Description
Get the current IMAP resource connection.
### Method
GET
### Endpoint
/webklex/php-imap/getConnection
### Response
#### Success Response (200)
- **connection** (resource) - The IMAP connection resource.
#### Response Example
```json
{
"connection": "[IMAP Resource]"
}
```
```
```APIDOC
## isConnected
### Description
Determine if a connection to the IMAP server has been established.
### Method
GET
### Endpoint
/webklex/php-imap/isConnected
### Response
#### Success Response (200)
- **isConnected** (bool) - True if connected, false otherwise.
#### Response Example
```json
{
"isConnected": true
}
```
```
```APIDOC
## checkConnection
### Description
Determine if the connection was established and connect if it was not.
### Method
POST
### Endpoint
/webklex/php-imap/checkConnection
```
```APIDOC
## connect
### Description
Connect to the IMAP server.
### Method
POST
### Endpoint
/webklex/php-imap/connect
```
```APIDOC
## reconnect
### Description
Terminate the current connection and reconnect to the IMAP server.
### Method
POST
### Endpoint
/webklex/php-imap/reconnect
```
```APIDOC
## disconnect
### Description
Disconnect from the IMAP server.
### Method
POST
### Endpoint
/webklex/php-imap/disconnect
```
--------------------------------
### Listen for New Messages with Idle
Source: https://github.com/webklex/php-imap/wiki/Idle
Use the idle method to listen for new messages. A callback function is executed for each new message received, providing access to message details like the subject.
```php
/** @var \Webklex\PHPIMAP\Folder $oFolder */
$oFolder->idle(function($message){
echo $message->subject."\n";
});
```
--------------------------------
### List All Folders
Source: https://github.com/webklex/php-imap/wiki/Folder---Mailbox
Retrieves a collection of all available folders within the IMAP account.
```APIDOC
## List All Available Folders
### Description
Retrieves a collection of all available folders (mailboxes) within the IMAP account.
### Method
GET (conceptual, as this is a client-side operation)
### Endpoint
N/A (Client-side operation)
### Parameters
None
### Request Example
```php
/** @var \Webklex\PHPIMAP\Client $oClient */
$aFolder = $oClient->getFolders();
```
### Response
#### Success Response (200)
- **aFolder** (FolderCollection) - A collection object containing all available folders.
```
--------------------------------
### Folder Management API
Source: https://github.com/webklex/php-imap/wiki/Client::class
API endpoints for retrieving, opening, and creating folders on the IMAP server.
```APIDOC
## getFolder
### Description
Get a Folder instance by its name.
### Method
GET
### Endpoint
/webklex/php-imap/getFolder
### Parameters
#### Query Parameters
- **folder_name** (string) - Required - The name of the folder to retrieve.
- **attributes** (int) - Optional - Folder attributes (default is 32).
- **delimiter** (string or null) - Optional - The folder delimiter.
- **prefix_address** (bool) - Optional - Whether to prefix the address.
### Response
#### Success Response (200)
- **folder** (object) - A Folder object representing the specified folder.
#### Response Example
```json
{
"folder": {
"name": "INBOX",
"messages": 100,
"recent": 5
}
}
```
```
```APIDOC
## getFolders
### Description
Get a list of folders. Can return a hierarchical tree or a flat array.
### Method
GET
### Endpoint
/webklex/php-imap/getFolders
### Parameters
#### Query Parameters
- **hierarchical** (bool) - Optional - If true, returns a tree of folders; otherwise, a flat array (default is false).
- **parent_folder** (string or null) - Optional - The parent folder to list subfolders from.
### Response
#### Success Response (200)
- **folders** (array) - A collection of Folder objects.
#### Response Example
```json
{
"folders": [
{
"name": "INBOX",
"messages": 100
},
{
"name": "Sent",
"messages": 50
}
]
}
```
```
```APIDOC
## openFolder
### Description
Open a given folder for operations.
### Method
POST
### Endpoint
/webklex/php-imap/openFolder
### Parameters
#### Request Body
- **folder** (string or Folder object) - Required - The name or Folder object of the folder to open.
- **attempts** (integer) - Optional - The number of attempts to open the folder.
### Request Example
```json
{
"folder": "INBOX",
"attempts": 3
}
```
```
```APIDOC
## createFolder
### Description
Create a new folder on the IMAP server.
### Method
POST
### Endpoint
/webklex/php-imap/createFolder
### Parameters
#### Request Body
- **name** (string) - Required - The name of the new folder to create.
### Request Example
```json
{
"name": "NewFolder"
}
```
### Response
#### Success Response (200)
- **created** (boolean) - True if the folder was created successfully, false otherwise.
#### Response Example
```json
{
"created": true
}
```
```
--------------------------------
### Configure Live Mailbox Testing
Source: https://github.com/webklex/php-imap/blob/master/README.md
To disable tests requiring a live mailbox, copy `phpunit.xml.dist` to `phpunit.xml` and adjust the configuration to set `LIVE_MAILBOX` to `false`.
```xml
```
--------------------------------
### Parent Object Methods
Source: https://github.com/webklex/php-imap/wiki/Mask::class
Methods for retrieving and accessing parent object information.
```APIDOC
## GET /webklex/php-imap/getParent
### Description
Retrieves the masked parent object.
### Method
GET
### Endpoint
/webklex/php-imap/getParent
### Parameters
#### Path Parameters
None
#### Query Parameters
None
### Response
#### Success Response (200)
- **parent** (Masked parent object) - The masked parent object.
#### Response Example
```json
{
"parent": "masked_parent_object_data"
}
```
```
```APIDOC
## GET /webklex/php-imap/getAttributes
### Description
Retrieves all cloned attributes of the parent object.
### Method
GET
### Endpoint
/webklex/php-imap/getAttributes
### Parameters
#### Path Parameters
None
#### Query Parameters
None
### Response
#### Success Response (200)
- **attributes** (array) - An array containing all cloned attributes.
#### Response Example
```json
{
"attributes": [
"attribute1",
"attribute2"
]
}
```
```
--------------------------------
### Copy Message to Another Folder
Source: https://context7.com/webklex/php-imap/llms.txt
Creates a copy of the current message in a specified destination folder. Returns true on success and false on failure.
```php
// Copy message to another folder
if ($message->copy('INBOX.Backup') === true) {
echo "Message copied successfully\n";
}
```
--------------------------------
### Fetch Messages Without Body, Flag, and Attachment Fetching
Source: https://github.com/webklex/php-imap/wiki/Advanced-fetching
Further optimize by disabling flag and attachment fetching using `setFetchFlags(false)` and `setFetchBody(false)`. This is ideal for minimal data retrieval, such as simple message counts or existence checks.
```php
/** @var \Webklex\PHPIMAP\Folder $oFolder */
/** @var \Webklex\PHPIMAP\Support\MessageCollection $aMessage */
$aMessage = $oFolder->query()->whereText('Hello world')
->setFetchFlags(false)
->setFetchBody(false)
->get();
/** @var \Webklex\PHPIMAP\Support\MessageCollection $aMessage */
$aMessage = $oFolder->query()->whereAll()
->setFetchFlags(false)
->setFetchBody(false)
->get();
```
--------------------------------
### Query All Messages in a Folder
Source: https://context7.com/webklex/php-imap/llms.txt
Retrieves all messages within the current folder. Ensure the folder object is properly initialized.
```php
query()->all()->get();
```
--------------------------------
### Count All Messages in Folder
Source: https://github.com/webklex/php-imap/wiki/Counting-messages
Use this to count all available messages within the current folder. Ensure the folder object is properly initialized.
```php
/** @var \Webklex\PHPIMAP\Folder $oFolder */
//Count all messages
/** @var \Webklex\PHPIMAP\Support\MessageCollection $aMessage */
$count = $oFolder->query()->all()->count();
```
--------------------------------
### Access Message Properties
Source: https://context7.com/webklex/php-imap/llms.txt
Demonstrates how to retrieve common email properties such as subject, sender, date, UID, and size from a fetched message object.
```php
// Access message properties
echo "Subject: " . $message->getSubject() . "\n";
echo "From: " . $message->getFrom()[0]->mail . "\n";
echo "Date: " . $message->getDate() . "\n";
echo "UID: " . $message->getUid() . "\n";
echo "Size: " . $message->getSize() . " bytes\n";
```
--------------------------------
### Mailbox Utility Methods
Source: https://github.com/webklex/php-imap/wiki/Folder::class
Utility methods for interacting with the IMAP client and performing advanced queries.
```APIDOC
## GET /mailbox/getClient
### Description
Get the current Client instance associated with this mailbox.
### Method
GET
### Endpoint
/mailbox/getClient
### Parameters
None
### Response
#### Success Response (200)
- **Client**: The Client instance object.
#### Response Example
```json
{
"client_instance": "..."
}
```
## GET /mailbox/query
### Description
Get the current Client instance. This method is aliased by Folder::messages() and Folder::search().
### Method
GET
### Endpoint
/mailbox/query
### Parameters
#### Query Parameters
- **charset** (string) - Optional - The character set to use for the query. Defaults to 'UTF-8'.
### Response
#### Success Response (200)
- **WhereQuery**: An object that can be used to construct and execute search queries.
#### Response Example
```json
{
"query_object": "..."
}
```
```
--------------------------------
### Optimize Fetching: Headers Only
Source: https://context7.com/webklex/php-imap/llms.txt
Improve performance by controlling which parts of an email are fetched. Disable body and flag fetching when only headers are required, reducing network traffic and memory usage. This is the fastest fetching method.
```php
query()
->whereText('Hello world')
->setFetchBody(false)
->get();
// Fetch all messages without body content
$messages = $folder->query()
->whereAll()
->setFetchBody(false)
->get();
// Fetch without body, flags, and attachments (fastest)
$messages = $folder->query()
->whereText('Hello world')
->setFetchFlags(false)
->setFetchBody(false)
->get();
// Process headers only
foreach ($messages as $message) {
echo $message->getSubject() . "\n";
echo $message->getFrom()[0]->mail . "\n";
echo $message->getDate() . "\n";
// Note: getHTMLBody() will be empty since body wasn't fetched
}
```
--------------------------------
### Connect with OAuth Authentication
Source: https://github.com/webklex/php-imap/wiki/oAuth
Use this snippet to establish a connection to an IMAP server using OAuth. Ensure 'oauth' is set as the authentication method and provide valid credentials for your email service.
```php
use Webklex\PHPIMAP\Clientmanager;
$cm = new Clientmanager();
/** @var \Webklex\PHPIMAP\Client $client */
$client = $cm->make([
'host' => 'imap.gmail.com',
'port' => 993,
'encryption' => 'ssl',
'validate_cert' => true,
'username' => 'example@gmail.com',
'password' => 'PASSWORD',
'authentication' => "oauth",
'protocol' => 'imap'
]);
//Connect to the IMAP Server
$client->connect();
```
--------------------------------
### Fetching and Counting Messages
Source: https://github.com/webklex/php-imap/wiki/WhereQuery::class
Methods for fetching messages, counting them, and controlling fetch options.
```APIDOC
## Fetching and Counting Messages
### Description
Methods for fetching messages, counting them, and controlling fetch options.
### Methods
#### `count()`
- **Description**: Count all available messages matching the current search criteria.
- **Return**: integer
#### `get()`
- **Description**: Fetch messages with the current query.
- **Return**: MessageCollection
#### `limit(integer $limit, integer $page = 1)`
- **Description**: Limit the amount of messages being fetched.
- **Parameters**:
- **limit** (integer) - Required - The maximum number of messages to fetch.
- **page** (integer) - Optional - The page number of results to fetch (defaults to 1).
- **Return**: WhereQuery
#### `setFetchOptions(boolean $fetch_options)`
- **Description**: Set the fetch options.
- **Parameters**:
- **fetch_options** (boolean) - Required - Whether to enable fetch options.
- **Return**: WhereQuery
#### `setFetchBody(boolean $fetch_body)`
- **Description**: Set the fetch body option.
- **Parameters**:
- **fetch_body** (boolean) - Required - Whether to fetch the message body.
- **Return**: WhereQuery
#### `setFetchFlags(boolean $fetch_flags)`
- **Description**: Set the fetch flags option.
- **Parameters**:
- **fetch_flags** (boolean) - Required - Whether to fetch the message flags.
- **Return**: WhereQuery
#### `leaveUnread()`
- **Description**: Do not mark all messages as "read" while fetching.
- **Return**: WhereQuery
#### `markAsRead()`
- **Description**: Mark all messages as "read" while fetching.
- **Return**: WhereQuery
```
--------------------------------
### Paginate IMAP Query
Source: https://github.com/webklex/php-imap/wiki/Pagination
Use this to paginate results directly from an IMAP query. Ensure you have a Folder instance and optionally specify search criteria like 'since'.
```php
/** @var \Webklex\PHPIMAP\Folder $oFolder */
/** @var \Illuminate\Pagination\LengthAwarePaginator $paginator */
$paginator = $oFolder->query()->since('15.03.2018')->paginate();
```
--------------------------------
### Build Custom Search Query with Array Syntax
Source: https://context7.com/webklex/php-imap/llms.txt
Constructs a search query using an array of criteria, allowing for more programmatic definition of search conditions. Supports various IMAP search keys.
```php
// Build custom search query with array syntax
$messages = $folder->query()
->where([['TEXT', 'Hello world'], ['SINCE', \Carbon\Carbon::parse('15.03.2018')]])
->get();
```
--------------------------------
### Run Docker Image for IMAP Server
Source: https://github.com/webklex/php-imap/blob/master/README.md
Run the Docker image for the IMAP server in detached mode, mapping port 993. The container will be automatically removed upon stopping.
```bash
docker run --name imap-server -p 993:993 --rm -d php-imap-server
```
--------------------------------
### Message Utility Methods
Source: https://github.com/webklex/php-imap/wiki/Message::class
Utility methods for checking message content and properties.
```APIDOC
## GET /webklex/php-imap/message/hasTextBody
### Description
Check if the Message has a text body.
### Method
GET
### Endpoint
/webklex/php-imap/message/hasTextBody
### Response
#### Success Response (200)
- **boolean** - True if the message has a text body, false otherwise.
#### Response Example
```json
{
"example": true
}
```
```
```APIDOC
## GET /webklex/php-imap/message/hasHTMLBody
### Description
Check if the Message has an HTML body.
### Method
GET
### Endpoint
/webklex/php-imap/message/hasHTMLBody
### Response
#### Success Response (200)
- **boolean** - True if the message has an HTML body, false otherwise.
#### Response Example
```json
{
"example": true
}
```
```
```APIDOC
## POST /webklex/php-imap/message/is
### Description
Does this message match another one?
### Method
POST
### Endpoint
/webklex/php-imap/message/is
### Arguments
- **message** (object) - The message to compare against.
### Response
#### Success Response (200)
- **boolean** - True if the messages match, false otherwise.
#### Response Example
```json
{
"example": true
}
```
```
--------------------------------
### Combine Multiple Search Criteria
Source: https://context7.com/webklex/php-imap/llms.txt
Chains multiple query methods to build complex search conditions. All specified criteria must be met for a message to be returned.
```php
// Combine multiple search criteria
$messages = $folder->query()
->unseen()
->from('support@example.com')
->since('01.01.2024')
->text('invoice')
->get();
```
--------------------------------
### Fetch Specific Message by UID
Source: https://github.com/webklex/php-imap/wiki/Fetch-a-specific-message
Retrieve a specific message from a folder using its message number (UID). Note that the UID is not guaranteed to be unique and can change.
```php
/** @var \Webklex\PHPIMAP\Folder $oFolder */
/** @var \Webklex\PHPIMAP\Message $oMessage */
$oMessage = $oFolder->query()->getMessage($msgn = 1);
```
--------------------------------
### Folder Path Retrieval
Source: https://github.com/webklex/php-imap/wiki/Client::class
Retrieves the current folder path.
```APIDOC
## GET /api/imap/folder/path
### Description
Get the current folder path.
### Method
GET
### Endpoint
/api/imap/folder/path
### Response
#### Success Response (200)
- **path** (string) - The current folder path.
#### Response Example
```json
{
"path": "/path/to/current/folder"
}
```
```