### Connect and Process Emails with PHP-IMAP
Source: https://www.php-imap.com/examples/getting-started
This PHP code snippet connects to an IMAP server using provided credentials, retrieves all mailboxes, iterates through each mailbox to fetch all messages, and then processes each message by displaying its subject, attachment count, and HTML body. Finally, it attempts to move the message to the 'INBOX.read' folder. This requires the Webklex/PHPIMAP library. It handles connecting, fetching, and moving emails.
```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->move('INBOX.read') == true){
echo 'Message has ben moved';
}else{
echo 'Message could not be moved';
}
}
}
```
--------------------------------
### Install PHP-IMAP with Composer
Source: https://www.php-imap.com/frameworks/laravel/installation
Installs the webklex/laravel-imap package using Composer. This is the primary method for adding the library to a Laravel project. You can also specify a particular version if needed.
```bash
composer require webklex/laravel-imap
```
```bash
composer require webklex/laravel-imap:2.2.0
```
--------------------------------
### Get All Messages in Chunks in PHP
Source: https://www.php-imap.com/api/query
Fetches all available email messages in manageable chunks to reduce request and response sizes. Be mindful of rate limits when using this.
```php
/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */
$query->all()->chunked(function($messages, $chunk){
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
dump("chunk #$chunk");
$messages->each(function($message){
/** @var \Webklex\PHPIMAP\Message $message */
dump($message->uid);
});
}, $chunk_size = 10, $start_chunk = 1);
```
--------------------------------
### Install Native PHP IMAP Module for Legacy Support
Source: https://www.php-imap.com/frameworks/laravel/installation
Installs the native php-imap module using apt-get, required for supporting legacy protocols like pop3 or nntp. This is followed by a graceful restart of the Apache server.
```bash
sudo apt-get install php*-imap
sudo apache2ctl graceful
```
--------------------------------
### Get All Messages in PHP
Source: https://www.php-imap.com/api/query
Retrieves a collection of all available email messages from the mailbox. This returns a `MessageCollection` object.
```php
/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $query->all()->get();
```
--------------------------------
### Install PHP Dependencies for PHP-IMAP
Source: https://www.php-imap.com/frameworks/laravel/installation
Installs the required mbstring and mcrypt PHP modules using apt-get, followed by gracefully restarting Apache. These modules are essential for the laravel-imap package to function correctly.
```bash
sudo apt-get install php*-mbstring php*-mcrypt
sudo apache2ctl graceful
```
--------------------------------
### Get Messages from Specific Sender in PHP
Source: https://www.php-imap.com/api/query
Retrieves a collection of all email messages sent from a particular email address. Replace 'example@domain.com' with the desired sender's email.
```php
/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $query->from('example@domain.com')->get();
```
--------------------------------
### PHP-IMAP: Create a New Client Instance
Source: https://www.php-imap.com/api/client-manager
Provides an example of creating a new client instance directly by passing an array of required account configuration details. This method is used when an account is not preconfigured.
```php
/** @var \Webklex\PHPIMAP\ClientManager $cm */
/** @var \Webklex\PHPIMAP\Client $client */
$client = $cm->make([
'host' => 'somehost.com',
'port' => 993,
'encryption' => 'ssl',
'validate_cert' => true,
'username' => 'username',
'password' => 'password',
'protocol' => 'imap'
]);
```
--------------------------------
### Publish PHP-IMAP Configuration File
Source: https://www.php-imap.com/frameworks/laravel/installation
Publishes the configuration file for the webklex/laravel-imap package to the config/imap.php location. This allows for customization of package settings. It uses the artisan vendor:publish command.
```bash
php artisan vendor:publish --provider="Webklex\IMAP\Providers\LaravelServiceProvider"
```
--------------------------------
### PHP-IMAP: Get a Preconfigured Account Client
Source: https://www.php-imap.com/api/client-manager
Illustrates how to retrieve a client instance for a preconfigured account using its identifier. This assumes accounts have been set up in the configuration.
```php
/** @var \Webklex\PHPIMAP\ClientManager $cm */
/** @var \Webklex\PHPIMAP\Client $client */
$client = $cm->account('account_identifier');
```
--------------------------------
### PHP-IMAP Google Gmail Connection with App Password
Source: https://www.php-imap.com/examples/oauth
Configuration for connecting to Google Gmail using an application-specific password. Users need to generate this password from their Google account security settings. The example shows the standard IMAP settings for Gmail.
```php
/** @var \Webklex\PHPIMAP\ClientManager $cm */
$client = $cm->make([
'host' => 'imap.googlemail.com',
'port' => 993,
'encryption' => 'ssl',
'validate_cert' => true,
'protocol' => 'imap',
'username' => 'username@gmail.com',
'password' => 'new-generated-password'
]);
```
--------------------------------
### Flag All Fetched Messages as Read in PHP
Source: https://www.php-imap.com/api/query
Automatically marks all fetched email messages as 'seen' on the server.
```php
/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */
$query->markAsRead();
```
--------------------------------
### Get Paginated Message Collection in PHP
Source: https://www.php-imap.com/api/query
Retrieves a paginated collection of email messages. This method is useful for displaying messages across multiple pages in a user interface.
```php
/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */
/** @var \Illuminate\Pagination\LengthAwarePaginator $paginator */
$paginator = $query->all()->paginate($per_page = 5, $page = null, $page_name = 'imap_page');
```
--------------------------------
### Get Messages Since Specific Date in PHP
Source: https://www.php-imap.com/api/query
Fetches all email messages sent after a specified date. Note that the IMAP protocol has limitations in searching by exact datetime keywords.
```php
/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $query->since('15.03.2018')->get();
$messages = $query->since(Carbon\Carbon::now()->subDays(5))->get();
```
--------------------------------
### Get Specific Message by ID in PHP
Source: https://www.php-imap.com/api/query
Retrieves a specific email message using its message number. Ensure the fetch option is configured for message number (`ST_MSGN`).
```php
/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */
/** @var \Webklex\PHPIMAP\Message $message */
$message = $query->getMessage($id = 1);
```
--------------------------------
### Count Messages Without Fetching in PHP
Source: https://www.php-imap.com/api/query
Counts the total number of available email messages without actually retrieving their content. This is an efficient way to get a message count.
```php
/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */
/** @var integer $count */
$count = $query->all()->count();
```
--------------------------------
### PHP-IMAP Outlook Office 365 OAuth Connection
Source: https://www.php-imap.com/examples/oauth
This code example illustrates connecting to Outlook/Office 365 using OAuth. It requires app registration in Azure AD and proper scope configuration. The 'host' is set to 'outlook.office365.com', and 'authentication' is set to 'oauth' with an access token provided as the password.
```php
/** @var \Webklex\PHPIMAP\ClientManager $cm */
$client = $cm->make([
'host' => 'outlook.office365.com',
'port' => 993,
'encryption' => 'ssl', // 'tls',
'validate_cert' => true,
'username' => 'xyz@outlook.com',
'password' => 'AccessToken',
'protocol' => 'imap',
'authentication' => "oauth",
]);
```
--------------------------------
### Set Fetch Sort Order in PHP
Source: https://www.php-imap.com/api/query
Defines the order in which fetched email messages are sorted. Supports both ascending ('asc') and descending ('desc') order.
```php
/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */
/** @var integer $count */
// Ascending
$query->setFetchOrder("asc");
$query->setFetchOrderAsc();
$query->fetchOrderAsc();
// Descending
$query->setFetchOrder("desc");
$query->setFetchOrderDesc();
$query->fetchOrderDesc();
```
--------------------------------
### Get Specific Message by Message Number in PHP
Source: https://www.php-imap.com/api/query
Retrieves a specific email message using its message number. This method is useful even if the fetch option is set to UID (`ST_UID`).
```php
/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */
/** @var \Webklex\PHPIMAP\Message $message */
$message = $query->getMessageByMsgn($msgn = 1);
```
--------------------------------
### Limit and Paginate Results in PHP
Source: https://www.php-imap.com/api/query
Limits the number of email messages returned and allows for pagination. This can significantly improve execution time by reducing the amount of data fetched.
```php
/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $query->all()->limit($limit = 10, $page = 2)->get();
// Example: Skip first 10 results and return the next 10.
```
--------------------------------
### PHP-IMAP OAuth Authentication
Source: https://www.php-imap.com/examples/oauth
This snippet demonstrates how to authenticate with an IMAP server using OAuth. It requires an access token, which should be provided as the 'password' and 'authentication' set to 'oauth'. This method is generally applicable for services supporting OAuth.
```php
/** @var \Webklex\PHPIMAP\ClientManager $cm */
$client = $cm->make([
'host' => 'some.host.tld',
'port' => 993,
'encryption' => 'ssl',
'validate_cert' => true,
'protocol' => 'imap',
'username' => 'username@host.tld',
'password' => 'ACCESS-TOKEN',
'authentication' => "oauth",
]);
```
--------------------------------
### PHP-IMAP: Get a Specific Configuration Value
Source: https://www.php-imap.com/api/client-manager
Demonstrates how to retrieve a specific configuration value from the ClientManager using a dotted key path. This allows easy access to individual settings.
```php
use Webklex\PHPIMAP\ClientManager;
$value = ClientManager::get('options.delimiter');
```
--------------------------------
### Get Specific Message by UID in PHP
Source: https://www.php-imap.com/api/query
Fetches a specific email message using its unique identifier (UID). This method works even if the fetch option is set to message number (`ST_MSGN`).
```php
/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */
/** @var \Webklex\PHPIMAP\Message $message */
$message = $query->getMessageByUid($uid = 1);
```
--------------------------------
### Configure PHP-IMAP Client with Proxy Authorization
Source: https://www.php-imap.com/examples/proxy
This snippet shows how to instantiate a PHP-IMAP client with proxy settings, including the proxy server address, port, and authentication credentials. It utilizes the `ClientManager` to create a client instance configured for secure IMAP communication through a proxy.
```php
/** @var \Webklex\PHPIMAP\Clientmanager $cm */
/** @var \Webklex\PHPIMAP\Client $client */
$client = $cm->make([
'host' => 'imap.somehost.com',
'port' => 993,
'encryption' => 'ssl',
'validate_cert' => true,
'username' => 'example@somehost.com',
'password' => 'Password',
'protocol' => 'imap',
'proxy' => [
'socket' => "tcp://proxy.com:3444",
'request_fulluri' => false,
'username' => "my_username",
'password' => "secret_password",
]
]);
```
--------------------------------
### Alternative Search Method Naming Schemes in PHP IMAP
Source: https://www.php-imap.com/api/query
Multiple naming conventions for the same search criteria provide flexibility in query construction. All methods (text(), Text(), whereText(), and array-based where()) produce equivalent results and return a MessageCollection.
```php
/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $query->text('hello world')->get();
$messages = $query->Text('hello world')->get();
$messages = $query->whereText('hello world')->get();
$messages = $query->where([['TEXT', 'Hello world']])->get();
```
--------------------------------
### Configure Service Provider and Alias for Older Laravel Versions
Source: https://www.php-imap.com/frameworks/laravel/installation
Manually adds the LaravelServiceProvider and Client alias to the config/app.php file for Laravel versions older than 5.5. This is necessary for package discovery not to handle automatically.
```php
Webklex\IMAP\Providers\LaravelServiceProvider::class,
```
```php
'Client' => Webklex\IMAP\Facades\Client::class,
```
--------------------------------
### Enable Soft Fail Mode for Bulk Fetching in PHP
Source: https://www.php-imap.com/api/query
Activates 'soft fail' mode to ignore specific exceptions during bulk message fetching. Any errors encountered can be retrieved using the `errors()` method.
```php
/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
/** @var [integer]\Exception $errors */
$messages = $query->all()->softFail()->get();
$errors = $query->errors();
```
--------------------------------
### Creating a Custom ImapIdleCommand for Specific Message Handling (PHP)
Source: https://www.php-imap.com/frameworks/laravel/commands
This example demonstrates how to create a custom Artisan command that extends `WebklexIMAPCommandsImapIdleCommand`. It defines a custom command signature (`custom_command`), specifies the IMAP account to use (`default`), and implements the `onNewMessage` callback to process each newly received email. This allows for tailored logic when new messages arrive.
```php
info("New message received: " . $message->subject);
}
}
```
--------------------------------
### Don't Flag All Fetched Messages as Read in PHP
Source: https://www.php-imap.com/api/query
Prevents the server from automatically marking all fetched email messages as 'seen'. Messages will remain unread.
```php
/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */
$query->leaveUnread();
```
--------------------------------
### IMAP Folder Details Response Structure
Source: https://www.php-imap.com/api/client
Example structure of the array returned by checkFolder() method, containing flags, message counts, UID validity, and next UID information for a folder.
```PHP
array:5 [
"flags" => array:1 [
0 => array:6 [
0 => "\\Answered"
1 => "\\Flagged"
2 => "\\Deleted"
3 => "\\Seen"
4 => "\\Draft"
]
]
"exists" => "65"
"recent" => "0"
"uidvalidity" => 1488899637
"uidnext" => 202
]
```
--------------------------------
### Get Address as String (PHP)
Source: https://www.php-imap.com/api/address
Demonstrates various methods to retrieve the string representation of an address object. This includes direct casting, magic methods, and a dedicated toString method. No external dependencies are required beyond the Address class instance.
```php
/** @var \Webklex\PHPIMAP\Address $address */
$value = "$address";
$value = (string)$address;
$value = $address->toString();
$value = $address->__toString();
```
--------------------------------
### Disable Message Body Fetching in PHP
Source: https://www.php-imap.com/api/query
Skips fetching the body content of email messages. This can be useful for long-running scripts or when the body is not required, potentially improving performance.
```php
/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */
$query->setFetchBody(false);
```
--------------------------------
### Get IMAP Folder Details
Source: https://www.php-imap.com/api/client
Retrieves detailed information about a specified folder including message count, next UID, and available flags. Returns an associative array with folder statistics and metadata.
```PHP
$info = $client->checkFolder($folder = 'INBOX.name');
```
--------------------------------
### Get Last Attribute Value (PHP)
Source: https://www.php-imap.com/api/attribute
Demonstrates how to get the last value stored within the attribute. Similar to `first()`, this method offers direct access to the final element in the attribute's values.
```php
/** @var \Webklex\PHPIMAP\Attribute $attribute */
$value = $attribute->last();
```
--------------------------------
### Get Attribute as Array (PHP)
Source: https://www.php-imap.com/api/attribute
Illustrates methods for converting an attribute object into an array. This allows for iterating over the attribute's values or accessing them using array-like notation.
```php
/** @var \Webklex\PHPIMAP\Attribute $attribute */
foreach($attribute as $key => $value) {
echo $value."\n";
}
$values = (array)$attribute;
$values = $attribute->toArray();
$values = $attribute->__serialize();
```
--------------------------------
### Search Messages by Text Content in PHP IMAP
Source: https://www.php-imap.com/api/query
Retrieve all messages containing specific text using the text() method. Returns a MessageCollection of matching messages. The query object must be properly initialized with a valid IMAP connection.
```php
/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $query->text('hello world')->get();
```
--------------------------------
### Chain Multiple Search Criteria in PHP IMAP
Source: https://www.php-imap.com/api/query
Combine multiple search criteria using method chaining to filter messages by sender, read status, and content simultaneously. The query executes all chained conditions with AND logic, returning only messages matching all criteria.
```php
/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $query->from('example@domain.com')->unseen()->text('hello world')->get();
```
--------------------------------
### Get All Attachments in PHP
Source: https://www.php-imap.com/api/message
Retrieves a collection of all files attached to the email message. This method returns an AttachmentCollection object and is available on the PHP-IMAP Message object.
```php
/** @var \Webklex\PHPIMAP\Message $message */
/** @var \Webklex\PHPIMAP\Support\AttachmentCollection $attachments */
$attachments = $message->getAttachments();
```
--------------------------------
### Get Attribute as String (PHP)
Source: https://www.php-imap.com/api/attribute
Demonstrates how to retrieve the string representation of an attribute object using various methods. This is useful for directly outputting or using the attribute's value as a string.
```php
/** @var \Webklex\PHPIMAP\Attribute $attribute */
$value = "$attribute";
$value = (string)$attribute;
$value = $attribute->toString();
$value = $attribute->__toString();
```
--------------------------------
### Negative Search Criteria in PHP IMAP
Source: https://www.php-imap.com/api/query
Search for messages that do NOT match specific criteria using not() or negative method names like notText(). Supports multiple negation syntaxes (camelCase, snake_case, and explicit not() chaining) for consistent query building across different search types.
```php
/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $query->notText('hello world')->get();
$messages = $query->not_text('hello world')->get();
$messages = $query->not()->text('hello world')->get();
```
--------------------------------
### Custom Search Criteria in PHP IMAP
Source: https://www.php-imap.com/api/query
Execute provider-specific custom search criteria using the where() method with array syntax. Enables access to IMAP server extensions and custom criteria not natively supported by the library, accepting string values as parameters.
```php
/** @var \Webklex\PHPIMAP\Query\WhereQuery $query */
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $query->where([["CUSTOM_FOOBAR" => "fooBar"]])->get();
```
--------------------------------
### Get Address as Array (PHP)
Source: https://www.php-imap.com/api/address
Illustrates how to obtain an array representation of an address object. This can be done by iterating over the object directly, casting it to an array, or using specific toArray and __serialize methods. Useful for processing individual address components.
```php
/** @var \Webklex\PHPIMAP\Address $address */
foreach($address as $key => $value) {
echo $value."\n";
}
$values = (array)$address;
$values = $address->toArray();
$values = $address->__serialize();
```
--------------------------------
### Get Containing Folder in PHP
Source: https://www.php-imap.com/api/message
Retrieves the folder object to which the current message belongs. This requires the PHP-IMAP Message object and returns a Folder instance.
```php
/** @var \Webklex\PHPIMAP\Message $message */
/** @var \Webklex\PHPIMAP\Folder $folder */
$folder = $message->getFolder();
```
--------------------------------
### Get File Extension from Attachment - PHP-IMAP
Source: https://www.php-imap.com/api/attachment
Attempts to identify and retrieve the file extension of the attachment based on its type or name. Returns a string containing the extension or null if it cannot be determined.
```php
/** @var \Webklex\PHPIMAP\Attachment $attachment */
/** @var string|null $ext */
$ext = $attachment->getExtension();
```
--------------------------------
### Get Message Flags in PHP
Source: https://www.php-imap.com/api/message
Retrieves all flags associated with the current message. This method returns a FlagCollection object and is available on the PHP-IMAP Message object.
```php
/** @var \Webklex\PHPIMAP\Message $message */
/** @var \Webklex\PHPIMAP\Support\FlagCollection $flags */
$flags = $message->getFlags();
```
--------------------------------
### Get Folder Message Overview in PHP-IMAP
Source: https://www.php-imap.com/api/folder
Retrieves a quick overview of all messages in the folder matching a given sequence range. Accepts a sequence parameter (default "1:*" for all messages) and returns an array of message metadata including headers, flags, and content information.
```php
/** @var \Webklex\PHPIMAP\Folder $folder */
/** @var array $overview */
$overview = $folder->overview($sequence = "1:*");
```
--------------------------------
### Create Custom Message Mask
Source: https://www.php-imap.com/api/mask
Provides an example of creating a custom message mask by extending the default `MessageMask` class. This allows for adding new methods like `token` and `getAttachmentCount` to enhance message processing.
```php
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]);
}
/**
* Get number of message attachments
* @return integer
*/
public function getAttachmentCount() {
return $this->getAttachments()->count();
}
}
```
--------------------------------
### Get First Attribute Value (PHP)
Source: https://www.php-imap.com/api/attribute
Provides the method to retrieve the very first value from the attribute's collection of values. This is a convenient way to access the initial item without iterating.
```php
/** @var \Webklex\PHPIMAP\Attribute $attribute */
$value = $attribute->first();
```
--------------------------------
### Get Raw Message Body in PHP
Source: https://www.php-imap.com/api/message
Fetches the complete, unparsed content of the email message body. This method returns the raw body as a string and is provided by the PHP-IMAP Message object.
```php
/** @var \Webklex\PHPIMAP\Message $message */
/** @var string $raw */
$raw = $message->getRawBody();
```
--------------------------------
### Create Custom Attachment Mask
Source: https://www.php-imap.com/api/mask
Shows how to create a custom attachment mask by extending `AttachmentMask`. This example includes a `token` method for generating a unique identifier and a `custom_save` method for saving attachments with specific naming conventions.
```php
class CustomAttachmentMask extends \Webklex\PHPIMAP\Support\Masks\AttachmentMask {
/**
* New custom method which can be called through a mask
* @return string
*/
public function token(){
return implode('-', [$this->id, $this->getMessage()->getUid(), $this->name]);
}
/**
* Custom attachment saving method
* @return bool
*/
public function custom_save() {
$path = "foo".DIRECTORY_SEPARATOR."bar".DIRECTORY_SEPARATOR;
$filename = $this->token();
return file_put_contents($path.$filename, $this->getContent()) !== false;
}
}
```
--------------------------------
### Get MIME Type from Attachment - PHP-IMAP
Source: https://www.php-imap.com/api/attachment
Attempts to identify and retrieve the MIME type of the attachment. Returns a string representing the MIME type (e.g., 'text/plain', 'application/pdf') or null if the type cannot be determined.
```php
/** @var \Webklex\PHPIMAP\Attachment $attachment */
/** @var string|null $mime */
$mime = $attachment->getMimeType();
```
--------------------------------
### Get Folder Details and Metadata in PHP-IMAP
Source: https://www.php-imap.com/api/folder
Retrieves comprehensive metadata about the current folder including available flags, total message count, recent message count, UID validity, and next UID. Returns an associative array with folder examination data.
```php
/** @var \Webklex\PHPIMAP\Folder $folder */
/** @var array $info */
$info = $folder->examine();
```
--------------------------------
### Get All Attachment Attributes - PHP-IMAP
Source: https://www.php-imap.com/api/attachment
Retrieves a complete array of all available attachment attributes, including parsed header attributes. The array contains properties such as content, type, content_type, name, disposition, size, and more.
```php
/** @var \Webklex\PHPIMAP\Attachment $attachment */
/** @var array $attributes */
$attributes = $attachment->getAttributes();
// Example result:
// array:9 [
// "content" => "some sample text\n"
// "type" => "text"
// "part_number" => 2
// "content_type" => "text/plain"
// "id" => null
// "name" => "test.txt"
// "disposition" => "attachment"
// "img_src" => null
// "size" => 24
// ]
```
--------------------------------
### Get All Message Attributes in PHP
Source: https://www.php-imap.com/api/message
Retrieves a list of all available attributes for the message, including parsed header attributes. This method returns an array of Attribute objects and is part of the PHP-IMAP Message object.
```php
/** @var \Webklex\PHPIMAP\Message $message */
/** @var \Webklex\PHPIMAP\Attribute[] $attributes */
$attributes = $message->getAttributes();
```
--------------------------------
### Get Message Header in PHP
Source: https://www.php-imap.com/api/message
Retrieves the parsed Header instance for the email message. This allows access to email headers like 'From', 'To', 'Subject', etc. It's a method of the PHP-IMAP Message object.
```php
/** @var \Webklex\PHPIMAP\Message $message */
/** @var \Webklex\PHPIMAP\Header $header */
$header = $message->getHeader();
```
--------------------------------
### Access Specific Attachment Attributes - PHP-IMAP
Source: https://www.php-imap.com/api/attachment
Demonstrates multiple methods to access individual attachment attributes (e.g., attachment name). Any attribute from the attachment's attributes array can be accessed using property access, getter methods, the get() method, or direct array access.
```php
/** @var \Webklex\PHPIMAP\Attachment $attachment */
/** @var string $name */
$name = $attachment->name;
$name = $attachment->getName();
$name = $attachment->get("name");
$name = $attachment->getAttributes()["name"];
```
--------------------------------
### Access Message Subject Attribute using PHP IMAP
Source: https://www.php-imap.com/api/message
This snippet shows multiple ways to access the subject attribute of an email message using the WebklexPHPIMAP library. It covers direct property access, the `getSubject()` method, the generic `get()` method, and accessing the attributes array directly. Ensure the `WebklexPHPIMAPMessage` and `WebklexPHPIMAPAttribute` classes are available in your scope.
```php
/** @var \Webklex\PHPIMAP\Message $message */
/** @var \Webklex\PHPIMAP\Attribute $subject */
$subject = $message->subject;
$subject = $message->getSubject();
$subject = $message->get("subject");
$subject = $message->getAttributes()["subject"];
```
--------------------------------
### PHP-IMAP: Instantiate ClientManager from Config File
Source: https://www.php-imap.com/api/client-manager
Demonstrates how to create a new ClientManager instance by providing the path to the configuration file. This method is suitable when you have a dedicated configuration file for your IMAP settings.
```php
use Webklex\PHPIMAP\ClientManager;
$cm = new ClientManager('path/to/config/imap.php');
```
--------------------------------
### PHP-IMAP: Instantiate ClientManager from Array
Source: https://www.php-imap.com/api/client-manager
Shows how to initialize the ClientManager using an associative array containing configuration options. This is useful when you prefer to manage configuration directly within your code rather than using a separate file.
```php
use Webklex\PHPIMAP\ClientManager;
$cm = new ClientManager($options = []);
```
--------------------------------
### Connect to IMAP Server
Source: https://www.php-imap.com/api/client
Establishes a connection to the IMAP server. This method must be called before any other operations can be performed on the client instance.
```PHP
$client->connect();
```
--------------------------------
### Registering ImapIdleCommand in Laravel Console Kernel (PHP)
Source: https://www.php-imap.com/frameworks/laravel/commands
This code snippet shows how to register the `ImapIdleCommand` from the `WebklexIMAP` package into your Laravel application's `app/Console/Kernel.php` file. This is the first step for enabling the event-driven approach to background IMAP processing. It ensures that the `imap:idle` Artisan command is available for use.
```php
getFolders($hierarchical = true);
```
--------------------------------
### Find IMAP Folder by Name or Path
Source: https://www.php-imap.com/api/client
Flexible folder retrieval method that accepts either a folder name or full path. Optional delimiter parameter can be specified if needed. Returns the first matching folder.
```PHP
$folder = $client->getFolder($folder = "INBOX.name", $delimiter = null);
$folder = $client->getFolder($folder = "name", $delimiter = null);
```
--------------------------------
### Registering CustomImapIdleCommand in Laravel Console Kernel (PHP)
Source: https://www.php-imap.com/frameworks/laravel/commands
This code snippet illustrates how to register a custom Artisan command, `CustomImapIdleCommand`, within your Laravel application's `app/Console/Kernel.php` file. By adding the custom command's class to the `$commands` array, you make it executable via the Artisan CLI, allowing you to run your personalized IMAP idle process.
```php
getFolderByName('name');
```
--------------------------------
### Find IMAP Folder by Path
Source: https://www.php-imap.com/api/client
Retrieves a specific folder using its complete path. The delimiter used in the path depends on the IMAP server configuration (e.g., 'INBOX.name').
```PHP
$folder = $client->getFolderByPath('INBOX.name');
```
--------------------------------
### Create New IMAP Folder
Source: https://www.php-imap.com/api/client
Creates a new folder on the IMAP server. The expunge parameter controls whether to expunge the current session; when true, the new folder may not be immediately recognized in the current session.
```PHP
$folder = $client->createFolder($folder = 'INBOX.name', $expunge = true);
```
--------------------------------
### Registering Custom Events in PHP-IMAP
Source: https://www.php-imap.com/api/event
This code demonstrates how to register a custom event, CustomMessageNewEvent, within the PHP-IMAP library. It shows how to set the custom event for 'message new' events either globally on the client instance or specifically on a folder instance. This allows developers to hook into specific library actions with their custom logic.
```php
/** @var \Webklex\PHPIMAP\Client $client */
/** @var \Webklex\PHPIMAP\Folder $folder */
$client->setEvent("message", "new", CustomMessageNewEvent::class);
$folder->setEvent("message", "new", CustomMessageNewEvent::class);
```
--------------------------------
### Custom Message New Event Implementation in PHP
Source: https://www.php-imap.com/api/event
This snippet demonstrates how to create a custom event that extends the base MessageNewEvent class. It customizes the event's behavior by overriding the constructor to process the new message and print its subject. This allows for specific actions to be performed when a new message event occurs.
```php
class CustomMessageNewEvent extends Webklex\PHPIMAP\Events\MessageNewEvent {
/**
* Create a new event instance.
* @var \Webklex\PHPIMAP\Message[] $messages
* @return void
*/
public function __construct($messages) {
$this->message = $messages[0];
echo "New message: ".$this->message->subject."\n";
}
}
```
--------------------------------
### Display Paginated PHP-IMAP Messages in HTML Table (PHP)
Source: https://www.php-imap.com/examples/pagination
This code provides an HTML table structure to display paginated messages fetched via PHP-IMAP. It iterates through the `LengthAwarePaginator` object, displaying message UID, subject, sender, and attachment status. It also includes logic to show a 'No messages found' message if the collection is empty and renders pagination links.
```html
| UID | Subject | From | Attachments |
|---|---|---|---|
| getUid(); ?> | getSubject(); ?> | getFrom()) ? $message->getFrom()[0]->mail : 'N/A'; ?> | getAttachments()->count() > 0 ? 'yes' : 'no'; ?> |
| No messages found | |||