### Connect to IMAP server and fetch emails using PHP
Source: https://github.com/barbushin/php-imap/wiki/Getting-Started
This snippet demonstrates how to connect to an IMAP server (specifically Gmail) using the PHP IMAP library, search for emails, and parse their content. It includes handling attachments, setting server encoding, and marking emails as read. Requires the PhpImap library to be installed.
```php
// Connect to server imap.gmail.com via SSL on port 993 and open the 'INBOX' folder
// Authenticate with the username / email address 'some@gmail.com'
// Save attachments to the directory '__DIR__'
// Set server encoding to 'US-ASCII'
$mailbox = new PhpImap\Mailbox(
'{imap.gmail.com:993/imap/ssl}INBOX', // IMAP server and mailbox folder
'some@gmail.com', // Username for the before configured mailbox
'*********', // Password for the before configured username
__DIR__, // Directory, where attachments will be saved (optional)
'US-ASCII' // Server encoding (optional)
);
try {
// Search in mailbox folder for specific emails
// PHP.net imap_search criteria: http://php.net/manual/en/function.imap-search.php
// Here, we search for "all" emails
$mails_ids = $mailbox->searchMailbox('ALL');
} catch(PhpImap\Exceptions\ConnectionException $ex) {
echo "IMAP connection failed: " . $ex;
die();
}
// Change default path delimiter '.' to '/'
$mailbox->setPathDelimiter('/');
// Switch server encoding
$mailbox->setServerEncoding('UTF-8');
// Change attachments directory
// Useful, when you did not set it at the beginning or
// when you need a different folder for eg. each email sender
$mailbox->setAttachmentsDir('/var/www/example.com/ticket-system/imap/attachments');
// Disable processing of attachments, if you do not require the attachments
// This significantly improves the performance
$mailbox->setAttachmentsIgnore(true);
// Loop through all emails
foreach($mails_ids as $mail_id) {
// Just a comment, to see, that this is the begin of an email
echo "+------ P A R S I N G ------+\n";
// Get mail by $mail_id
$email = $mailbox->getMail(
$mail_id, // ID of the email, you want to get
false // Do NOT mark emails as seen
);
echo "from-name: " . (isset($email->fromName)) ? $email->fromName : $email->fromAddress;
echo "from-email: " . $email->fromAddress;
echo "to: " . $email->to;
echo "subject: " . $email->subject;
echo "message_id: " . $email->messageId;
echo "mail has attachments? ";
if($email->hasAttachments()) {
echo "Yes\n";
} else {
echo "No\n";
}
if(!empty($email->getAttachments())) {
echo count($email->getAttachments()) . " attachements";
}
if($email->textHtml) {
echo "Message HTML:\n" . $email->textHtml;
} else {
echo "Message Plain:\n" . $email->textPlain;
}
if(!empty($email->autoSubmitted)) {
// Mark email as "read" / "seen"
$mailbox->markMailAsRead($mail_id);
echo "+------ IGNORING: Auto-Reply ------+";
}
if(!empty($email->precedence)) {
// Mark email as "read" / "seen"
$mailbox->markMailAsRead($mail_id);
echo "+------ IGNORING: Non-Delivery Report/Receipt ------+";
}
}
// Disconnect from mailbox
$mailbox->disconnect();
```
--------------------------------
### Fetch and Display Emails with Attachments - PHP
Source: https://github.com/barbushin/php-imap/wiki/Examples-of-usage
This comprehensive example demonstrates connecting to a Gmail IMAP server, searching for emails within the INBOX since a specific date, sorting them, and then iterating through a subset of the latest emails. For each email, it fetches and displays the header (subject, sender, date) and the body (HTML or plain text), and also loads any attachments.
```php
searchMailbox('SINCE "20170101"');
if(!$mailsIds) exit('Mailbox is empty');
// Show the total number of emails loaded
echo 'n= '.count($mailsIds).'
';
// Put the latest email on top of listing
rsort($mailsIds);
// Get the last 15 emails only
array_splice($mailsIds, 15);
// Loop through emails one by one
foreach($mailsIds as $num) {
// Show header with subject and data on this email
$head = $mailbox->getMailHeader($num);
echo '
';
echo $head->subject.' (';
if (isset($head->fromName)) echo 'by '.$head->fromName.' on ';
elseif (isset($head->fromAddress)) echo 'by '.$head->fromAddress.' on ';
echo $head->date.')';
echo '
';
// Show the main body message text
// Do not mark email as seen
$markAsSeen = false;
$mail = $mailbox->getMail($num, $markAsSeen);
if ($mail->textHtml)
echo $mail->textHtml;
else
echo $mail->textPlain;
echo '
';
// Load eventual attachment into attachments directory
$mail->getAttachments();
}
$mailbox->disconnect();
?>
```
--------------------------------
### Handle Email Attachments with PHP IMAP
Source: https://context7.com/barbushin/php-imap/llms.txt
Shows how to manage email attachments with options for saving to disk or processing in memory. Includes examples for getting attachment contents, metadata, and controlling attachment handling behavior.
```php
setAttachmentFilenameMode(true);
try {
$mailsIds = $mailbox->searchMailbox('ALL');
foreach ($mailsIds as $mailId) {
$mail = $mailbox->getMail($mailId);
if ($mail->hasAttachments()) {
$attachments = $mail->getAttachments();
foreach ($attachments as $attachment) {
echo "Processing: " . $attachment->name . "\n";
// Get file content without saving
$content = $attachment->getContents();
// Get file metadata
echo " MIME Type: " . $attachment->mimeType . "\n";
echo " Size: " . $attachment->sizeInBytes . " bytes\n";
echo " Encoding: " . $attachment->encoding . "\n";
echo " Content ID: " . $attachment->contentId . "\n";
echo " Disposition: " . $attachment->disposition . "\n";
// Get file info using fileinfo constants
echo " File type: " . $attachment->getFileInfo(FILEINFO_MIME_TYPE) . "\n";
// Attachment is already saved to disk if attachmentsDir was set
if ($attachment->filePath) {
echo " Saved to: " . $attachment->filePath . "\n";
// Process file (e.g., move to another location)
$newPath = __DIR__ . '/processed/' . basename($attachment->filePath);
copy($attachment->filePath, $newPath);
}
// Remove attachment from memory after processing
$mail->removeAttachment($attachment->id);
}
}
}
// Ignore attachments for performance (only get email text)
$mailbox->setAttachmentsIgnore(true);
$mailNoAttachments = $mailbox->getMail($mailsIds[0]);
} catch (Exception $ex) {
echo "Error: " . $ex->getMessage() . "\n";
}
```
--------------------------------
### Create new PhpImap Mailbox instance
Source: https://github.com/barbushin/php-imap/wiki/Getting-Started
Initializes a new instance of the PhpImap\Mailbox class with basic IMAP connection parameters. The last two parameters are optional with default values for attachment directory and server encoding.
```php
$mailbox = new PhpImap\Mailbox(
$imapPath, // IMAP server and mailbox folder
$login, // Username for the before configured mailbox
$password, // Password for the before configured username
$attachmentsDir = null, // Directory, where attachments will be saved (optional)
$serverEncoding = 'UTF-8' // Server encoding (optional)
);
```
--------------------------------
### Check Mailbox Info - PHP
Source: https://github.com/barbushin/php-imap/wiki/Examples-of-usage
This example shows how to connect to an IMAP server and retrieve general mailbox information, such as the server's current time. It uses the PhpImapMailbox class and specifically the `checkMailbox()` method, which corresponds to the IMAP `imap_check()` function.
```php
$mailbox = new PhpImap\Mailbox(
'{outlook.office365.com:993/imap/ssl}',
'example@gmail.com',
'password',
__DIR__,
'US-ASCII' // force charset different from UTF-8
);
// Calls imap_check();
// http://php.net/manual/en/function.imap-check.php
$info = $mailbox->checkMailbox();
// Show current time for the mailbox
$current_server_time = isset($info->Date) && $info->Date ? date('Y-m-d H:i:s', strtotime($info->Date)) : 'unknown';
echo $current_server_time;
```
--------------------------------
### Connect to IMAP mailbox and retrieve emails
Source: https://github.com/barbushin/php-imap/blob/master/README.md
Creates a Mailbox instance and retrieves emails from an IMAP server. Demonstrates basic setup with SSL connection to Gmail, authentication, and attachment handling. Shows how to search for emails and retrieve the first message with its attachments.
```php
// Create PhpImap\Mailbox instance for all further actions
$mailbox = new PhpImap\Mailbox(
'{imap.gmail.com:993/imap/ssl}INBOX', // IMAP server and mailbox folder
'some@gmail.com', // Username for the before configured mailbox
'*********', // Password for the before configured username
__DIR__, // Directory, where attachments will be saved (optional)
'UTF-8', // Server encoding (optional)
true, // Trim leading/ending whitespaces of IMAP path (optional)
false // Attachment filename mode (optional; false = random filename; true = original filename)
);
// set some connection arguments (if appropriate)
$mailbox->setConnectionArgs(
CL_EXPUNGE // expunge deleted mails upon mailbox close
| OP_SECURE // don't do non-secure authentication
);
try {
// Get all emails (messages)
// PHP.net imap_search criteria: http://php.net/manual/en/function.imap-search.php
$mailsIds = $mailbox->searchMailbox('ALL');
} catch(PhpImap\Exceptions\ConnectionException $ex) {
echo "IMAP connection failed: " . implode(",", $ex->getErrors('all'));
die();
}
// If $mailsIds is empty, no emails could be found
if(!$mailsIds) {
die('Mailbox is empty');
}
// Get the first message
// If '__DIR__' was defined in the first line, it will automatically
// save all attachments to the specified directory
$mail = $mailbox->getMail($mailsIds[0]);
// Show, if $mail has one or more attachments
echo "\nMail has attachments? ";
if($mail->hasAttachments()) {
echo "Yes\n";
} else {
echo "No\n";
}
// Print all information of $mail
print_r($mail);
// Print all attachements of $mail
echo "\n\nAttachments:\n";
print_r($mail->getAttachments());
```
--------------------------------
### List and Search Mailboxes - PHP
Source: https://github.com/barbushin/php-imap/wiki/Examples-of-usage
This snippet demonstrates how to connect to an IMAP server, retrieve a list of all mailboxes, and then search for emails within each mailbox based on a date range. It utilizes the PhpImapMailbox class and its methods for mailbox operations.
```php
$mailbox = new PhpImap\Mailbox(
'{imap.gmail.com:993/ssl/novalidate-cert/imap}',
'example@gmail.com',
'password',
false // when $attachmentsDir is false we don't save attachments
);
// get the list of folders/mailboxes
$folders = $mailbox->getMailboxes('*');
// loop through mailboxs
foreach($folders as $folder) {
// switch to particular mailbox
$mailbox->switchMailbox($folder['fullpath']);
// search in particular mailbox
$mails_ids[$folder['fullpath']] = $mailbox->searchMailbox('SINCE "24 Jan 2018" BEFORE "25 Jan 2018"');
}
var_dump($mails_ids);
```
--------------------------------
### IMAP connection with custom server encoding
Source: https://github.com/barbushin/php-imap/wiki/Getting-Started
Connects to Gmail's IMAP server with a custom server encoding set to US-ASCII instead of the default UTF-8. All other parameters are configured similar to previous examples.
```php
$mailbox = new PhpImap\Mailbox(
'{imap.gmail.com:993/imap/ssl}INBOX', // IMAP server and mailbox folder
'some@gmail.com', // Username for the before configured mailbox
'*********', // Password for the before configured username
__DIR__, // Directory, where attachments will be saved (optional)
'US-ASCII' // Server encoding (optional)
);
```
--------------------------------
### IMAP connection with automatic attachment saving
Source: https://github.com/barbushin/php-imap/wiki/Getting-Started
Connects to Gmail's IMAP server and automatically saves email attachments to the specified directory. Uses __DIR__ to save attachments in the same directory as the script.
```php
$mailbox = new PhpImap\Mailbox(
'{imap.gmail.com:993/imap/ssl}INBOX', // IMAP server and mailbox folder
'some@gmail.com', // Username for the before configured mailbox
'*********', // Password for the before configured username
__DIR__ // Directory, where attachments will be saved (optional)
);
```
--------------------------------
### SSL secured IMAP connection without attachments
Source: https://github.com/barbushin/php-imap/wiki/Getting-Started
Connects to Gmail's IMAP server on port 993 with SSL encryption, accessing the INBOX folder. Authentication is performed with the provided username and password.
```php
$mailbox = new PhpImap\Mailbox(
'{imap.gmail.com:993/imap/ssl}INBOX', // IMAP server incl. flags and optional mailbox folder
'some@gmail.com', // Username for the before configured mailbox
'*********' // Password for the before configured username
);
```
--------------------------------
### Check if email has attachments
Source: https://github.com/barbushin/php-imap/wiki/Getting-Started
Determines whether an email has attachments using the hasAttachments() method. This works even when attachment processing is disabled, though the actual attachment count is only available when processing is enabled.
```php
// Get any message
// In this example, we will just take the first one
$mail = $mailbox->getMail($mailsIds[0]);
// Show, if $mail has one or more attachments
echo "\nMail has attachments? ";
if($mail->hasAttachments()) {
echo "Yes\n";
} else {
echo "No\n";
}
```
--------------------------------
### Disable attachment processing for performance
Source: https://github.com/barbushin/php-imap/wiki/Getting-Started
Disables processing of email attachments to significantly improve performance when attachments are not needed. This prevents the library from parsing attachments during email fetching.
```php
$mailbox->setAttachmentsIgnore(true);
```
--------------------------------
### Deleting and Moving Emails (PHP)
Source: https://context7.com/barbushin/php-imap/llms.txt
This snippet demonstrates how to delete, move, and save emails using the PhpImap library. It shows how to mark emails for deletion, permanently delete them, move them between folders, and save them to a file. Requires PhpImap library and IMAP credentials. Also shows how to get mailbox and quota information.
```PHP
searchMailbox('SUBJECT "spam"');
if (!empty($mailsIds)) {
// Mark email for deletion (not permanently deleted yet)
$mailbox->deleteMail($mailsIds[0]);
// Permanently delete all marked emails
$mailbox->expungeDeletedMails();
// Move email to another folder
$mailbox->moveMail($mailsIds[1], 'Trash');
// Move multiple emails (use range)
$mailbox->moveMail(implode(',', array_slice($mailsIds, 2, 5)), 'Archive');
// Copy email to another folder
$mailbox->copyMail($mailsIds[0], 'Backup');
// Save email to file (in RFC822 .eml format)
$mailbox->saveMail($mailsIds[0], __DIR__ . '/saved_email.eml');
}
// Configure expunge on disconnect
$mailbox->setExpungeOnDisconnect(true); // Auto-expunge when disconnecting
// Get mailbox statistics
$info = $mailbox->getMailboxInfo();
echo "Total messages: " . $info->Nmsgs . "\n";
echo "Recent messages: " . $info->Recent . "\n";
echo "Unread messages: " . $info->Unread . "\n";
echo "Deleted messages: " . $info->Deleted . "\n";
echo "Mailbox size: " . $info->Size . " bytes\n";
// Get quota information
$quotaLimit = $mailbox->getQuotaLimit('INBOX');
$quotaUsage = $mailbox->getQuotaUsage('INBOX');
echo "Quota: " . $quotaUsage . " KB / " . $quotaLimit . " KB\n";
} catch (Exception $ex) {
echo "Error: " . $ex->getMessage() . "\n";
} finally {
$mailbox->disconnect();
}
```
--------------------------------
### Retrieve Email Messages with PHP IMAP
Source: https://context7.com/barbushin/php-imap/llms.txt
Demonstrates how to fetch complete email messages including headers, body content, and attachments using the php-imap library. Shows accessing email properties, checking for attachments, and getting raw email formats.
```php
searchMailbox('ALL');
if (!empty($mailsIds)) {
// Get the first email (mark as seen by default)
$mail = $mailbox->getMail($mailsIds[0]);
// Access email properties
echo "From: " . $mail->fromAddress . "\n";
echo "From Name: " . $mail->fromName . "\n";
echo "Subject: " . $mail->subject . "\n";
echo "Date: " . $mail->date . "\n";
echo "To: " . $mail->toString . "\n";
echo "Message ID: " . $mail->messageId . "\n";
// Get email body (lazy loaded)
echo "Plain Text Body:\n" . $mail->textPlain . "\n\n";
echo "HTML Body:\n" . $mail->textHtml . "\n\n";
// Check for attachments
if ($mail->hasAttachments()) {
echo "Email has " . count($mail->getAttachments()) . " attachment(s)\n";
foreach ($mail->getAttachments() as $attachment) {
echo "Attachment: " . $attachment->name . "\n";
echo " Size: " . $attachment->sizeInBytes . " bytes\n";
echo " Type: " . $attachment->mimeType . "\n";
echo " File path: " . $attachment->filePath . "\n";
}
}
// Get email without marking as seen
$mailUnread = $mailbox->getMail($mailsIds[1], false);
// Get only email header (faster, no body content)
$header = $mailbox->getMailHeader($mailsIds[2]);
echo "Subject: " . $header->subject . "\n";
echo "Is seen: " . ($header->isSeen ? 'Yes' : 'No') . "\n";
echo "Is flagged: " . ($header->isFlagged ? 'Yes' : 'No') . "\n";
// Get raw email in RFC822 format
$rawMail = $mailbox->getRawMail($mailsIds[0]);
// Get email in MBOX format
$mboxFormat = $mailbox->getMailMboxFormat($mailsIds[0]);
}
} catch (Exception $ex) {
echo "Error: " . $ex->getMessage() . "\n";
}
```
--------------------------------
### Marking Email Flags and Status (PHP)
Source: https://context7.com/barbushin/php-imap/llms.txt
This snippet demonstrates how to mark emails as read, unread, flagged, or deleted, and check the status of these flags using the PhpImap library. It requires the PhpImap library and valid IMAP credentials. The function provides examples for single and multiple email operations.
```PHP
searchMailbox('ALL');
if (!empty($mailsIds)) {
// Mark single email as read
$mailbox->markMailAsRead($mailsIds[0]);
// Mark single email as unread
$mailbox->markMailAsUnread($mailsIds[1]);
// Mark email as important (flagged)
$mailbox->markMailAsImportant($mailsIds[2]);
// Mark multiple emails as read
$mailbox->markMailsAsRead([$mailsIds[3], $mailsIds[4], $mailsIds[5]]);
// Mark multiple emails as unread
$mailbox->markMailsAsUnread([$mailsIds[6], $mailsIds[7]]);
// Mark multiple emails as important
$mailbox->markMailsAsImportant([$mailsIds[8], $mailsIds[9]]);
// Check if a flag is set
if ($mailbox->flagIsSet($mailsIds[0], '\Seen')) {
echo "Email is marked as read\n";
}
if ($mailbox->flagIsSet($mailsIds[2], '\Flagged')) {
echo "Email is flagged as important\n";
}
// Set custom flags
$mailbox->setFlag([$mailsIds[10]], '\Answered');
$mailbox->setFlag([$mailsIds[11]], '\Draft');
// Clear flags
$mailbox->clearFlag([$mailsIds[0]], '\Seen');
$mailbox->clearFlag([$mailsIds[2]], '\Flagged');
}
} catch (Exception $ex) {
echo "Error: " . $ex->getMessage() . "\n";
}
```
--------------------------------
### Advanced Configuration and Performance Optimization in PHP
Source: https://context7.com/barbushin/php-imap/llms.txt
Shows advanced configuration options for the PhpImap library including connection parameters, encoding settings, and performance optimizations for large mailbox operations. Covers attachment handling, search optimization, and connection management techniques.
```php
setServerEncoding('ISO-8859-1');
// Configure connection retry settings
$mailbox->setConnectionRetry(5); // Max retry attempts
$mailbox->setConnectionRetryDelay(500); // Delay in milliseconds
// Set path delimiter for mailbox hierarchy
$mailbox->setPathDelimiter('.'); // or '/' depending on server
// Configure IMAP search options
$mailbox->setImapSearchOption(SE_UID); // Search by UID (faster)
// Set attachments directory dynamically
$mailbox->setAttachmentsDir(__DIR__ . '/custom-attachments');
// Performance optimization: ignore attachments when not needed
$mailbox->setAttachmentsIgnore(true);
// Search and retrieve without downloading attachments (faster)
$mailsIds = $mailbox->searchMailbox('SINCE "1 Jan 2024"');
foreach ($mailsIds as $mailId) {
$mail = $mailbox->getMail($mailId);
echo $mail->subject . "\n";
// Attachments are not processed, saving time and memory
}
// Re-enable attachments when needed
$mailbox->setAttachmentsIgnore(false);
// Disable server encoding for specific searches (useful for Exchange servers)
$resultsWithoutEncoding = $mailbox->searchMailbox('FROM "test"', true);
// Get count of all messages without fetching them
$totalMessages = $mailbox->countMails();
echo "Total messages: $totalMessages\n";
// Get mailbox headers only (lightweight operation)
$headers = $mailbox->getMailboxHeaders();
foreach ($headers as $header) {
echo $header . "\n";
}
// Get mails info (overview without full body)
$mailsInfo = $mailbox->getMailsInfo(array_slice($mailsIds, 0, 10));
foreach ($mailsInfo as $info) {
echo "Subject: " . $info->subject . ", From: " . $info->from . "\n";
}
// Check connection status
if ($mailbox->hasImapStream()) {
echo "Connected\n";
}
// Get IMAP path
echo "Current IMAP path: " . $mailbox->getImapPath() . "\n";
// Get login info
echo "Logged in as: " . $mailbox->getLogin() . "\n";
} catch (Exception $ex) {
echo "Error: " . $ex->getMessage() . "\n";
} finally {
// Always disconnect when done
$mailbox->disconnect();
}
```
--------------------------------
### Manage Mailbox Folders with PHP IMAP
Source: https://context7.com/barbushin/php-imap/llms.txt
Demonstrates how to perform various mailbox folder operations including listing, creating, renaming, and deleting folders. Shows how to switch between mailboxes and retrieve mailbox status information. Requires PhpImap library and valid IMAP credentials.
```php
getMailboxes('*');
echo "Available folders:\n";
foreach ($folders as $folder) {
echo " " . $folder['shortpath'] . " (Full: " . $folder['fullpath'] . ")\n";
echo " Attributes: " . $folder['attributes'] . "\n";
echo " Delimiter: " . $folder['delimiter'] . "\n";
}
// Get only subscribed mailboxes
$subscribedFolders = $mailbox->getSubscribedMailboxes('*');
// Create a new mailbox/folder
$mailbox->createMailbox('Projects');
$mailbox->createMailbox('Projects/2024'); // Create subfolder
// Rename a mailbox
$mailbox->renameMailbox('Projects/2024', 'Projects/Archive2024');
// Delete a mailbox
$mailbox->deleteMailbox('Projects/Archive2024');
// Subscribe to a mailbox
$mailbox->subscribeMailbox('Projects');
// Unsubscribe from a mailbox
$mailbox->unsubscribeMailbox('Spam');
// Switch to different mailbox without reconnecting
$mailbox->switchMailbox('{imap.gmail.com:993/imap/ssl}Sent');
// Search in the new mailbox
$sentMailsIds = $mailbox->searchMailbox('ALL');
echo "Sent folder has " . count($sentMailsIds) . " messages\n";
// Get mailbox status
$status = $mailbox->statusMailbox();
echo "Messages: " . $status->messages . "\n";
echo "Recent: " . $status->recent . "\n";
echo "Unseen: " . $status->unseen . "\n";
echo "UIDnext: " . $status->uidnext . "\n";
// Iterate through all folders and search
$allFolders = $mailbox->getMailboxes('*');
$results = [];
foreach ($allFolders as $folder) {
$mailbox->switchMailbox($folder['fullpath']);
$results[$folder['shortpath']] = $mailbox->searchMailbox('SINCE "1 Jan 2024"');
}
foreach ($results as $folderName => $mailIds) {
echo $folderName . ": " . count($mailIds) . " messages since Jan 1, 2024\n";
}
} catch (Exception $ex) {
echo "Error: " . $ex->getMessage() . "\n";
}
```
--------------------------------
### Call PHP IMAP functions using imap() method
Source: https://github.com/barbushin/php-imap/blob/master/README.md
Demonstrates how to use the imap() method to call any PHP IMAP function within the mailbox instance context. Shows how to retrieve mailbox information and extract the server date/time.
```php
// Call imap_check() - see http://php.net/manual/function.imap-check.php
$info = $mailbox->imap('check');
// Show current time for the mailbox
$currentServerTime = isset($info->Date) && $info->Date ? date('Y-m-d H:i:s', strtotime($info->Date)) : 'Unknown';
echo $currentServerTime;
```
--------------------------------
### Upgrade from 3.x - Replace magic method with Imap class
Source: https://github.com/barbushin/php-imap/blob/master/README.md
Shows the code changes required when upgrading from version 3.x to later versions. Demonstrates how the magic imap() method was replaced with direct Imap class calls for better type safety and performance.
```php
Before:
```php
public function checkMailbox()
{
return $this->imap('check');
}
```
After:
```php
public function checkMailbox(): object
{
return Imap::check($this->getImapStream());
}
```
```
--------------------------------
### Optimize performance by ignoring attachments
Source: https://github.com/barbushin/php-imap/blob/master/README.md
Shows how to improve performance when attachments aren't needed by setting attachments ignore mode. Also demonstrates retrieving mailbox folders and searching within specific mailboxes.
```php
// If you don't need to grab attachments you can significantly increase performance of your application
$mailbox->setAttachmentsIgnore(true);
// get the list of folders/mailboxes
$folders = $mailbox->getMailboxes('*');
// loop through mailboxs
foreach($folders as $folder) {
// switch to particular mailbox
$mailbox->switchMailbox($folder['fullpath']);
// search in particular mailbox
$mails_ids[$folder['fullpath']] = $mailbox->searchMailbox('SINCE "1 Jan 2018" BEFORE "28 Jan 2018"');
}
print_r($mails_ids);
```
--------------------------------
### Connect to Mailbox via IMAP
Source: https://context7.com/barbushin/php-imap/llms.txt
Establishes a secure connection to an IMAP mailbox with authentication and configuration options. Requires PHP IMAP extension and valid server credentials. Supports custom attachment directories and encoding settings.
```php
setConnectionArgs(
CL_EXPUNGE | OP_SECURE, // Expunge on close and secure authentication
3 // Retry attempts
);
// Set connection timeouts (in seconds)
$mailbox->setTimeouts(30, [IMAP_OPENTIMEOUT, IMAP_READTIMEOUT, IMAP_WRITETIMEOUT]);
try {
// Test connection by checking mailbox
$info = $mailbox->checkMailbox();
echo "Connected successfully. Messages: " . $info->Nmsgs . "\n";
} catch (ConnectionException $ex) {
echo "Connection failed: " . implode(", ", $ex->getErrors('all')) . "\n";
}
```
--------------------------------
### Handle Inline Images in HTML Emails with PHP
Source: https://context7.com/barbushin/php-imap/llms.txt
Shows how to process inline images in HTML emails by either replacing Content-ID references with file paths or embedding images as base64 data URLs. Demonstrates methods for retrieving image placeholders and managing attachments. Requires PhpImap library and attachment storage directory.
```php
searchMailbox('ALL');
if (!empty($mailsIds)) {
$mail = $mailbox->getMail($mailsIds[0]);
// Get HTML with inline images referenced by Content-ID
$htmlWithCids = $mail->textHtml;
echo "Original HTML with CID references:\n";
echo $htmlWithCids . "\n\n";
// Method 1: Replace inline image references with file paths
$baseUri = 'https://example.com/email-images/';
$htmlWithLinks = $mail->replaceInternalLinks($baseUri);
echo "HTML with image links:\n";
echo $htmlWithLinks . "\n\n";
// Method 2: Embed images as base64 data URLs
$mail->embedImageAttachments();
$htmlWithEmbeddedImages = $mail->textHtml;
echo "HTML with embedded base64 images:\n";
echo $htmlWithEmbeddedImages . "\n\n";
// After embedding, inline image attachments are removed
echo "Remaining attachments: " . count($mail->getAttachments()) . "\n";
// Get placeholders for inline images
$placeholders = $mail->getInternalLinksPlaceholders();
foreach ($placeholders as $attachmentId => $placeholder) {
echo "Image CID: $attachmentId => Placeholder: $placeholder\n";
}
}
} catch (Exception $ex) {
echo "Error: " . $ex->getMessage() . "\n";
}
```
--------------------------------
### Append Messages to Mailbox in PHP
Source: https://context7.com/barbushin/php-imap/llms.txt
Demonstrates how to add new messages to a mailbox folder using the PhpImap library. Shows different methods including simple text messages, messages with flags, and structured envelope/body arrays. Requires valid IMAP credentials and mailbox access.
```php
appendMessageToMailbox($message, 'INBOX');
// Append to a specific folder with options
$mailbox->appendMessageToMailbox(
$message,
'Sent',
'\\Seen \\Flagged', // Message flags
date('d-M-Y H:i:s O') // Internal date
);
// Append using envelope and body array structure
$envelope = [
'subject' => 'Another Test'
];
$body = [
[
'type' => TYPETEXT,
'subtype' => 'plain',
'charset' => 'UTF-8',
'contents.data' => 'Message content here'
]
];
$mailbox->appendMessageToMailbox([$envelope, $body], 'INBOX');
echo "Messages appended successfully\n";
} catch (Exception $ex) {
echo "Error: " . $ex->getMessage() . "\n";
}
```
--------------------------------
### Search Emails with IMAP Criteria
Source: https://context7.com/barbushin/php-imap/llms.txt
Searches mailbox for emails matching specific IMAP search criteria including unseen messages, sender addresses, date ranges, and subjects. Supports complex queries and sorting with multiple results merging.
```php
searchMailbox('UNSEEN');
echo "Unseen emails: " . count($unseenMailsIds) . "\n";
// Search for emails from specific sender
$specificSenderIds = $mailbox->searchMailbox('FROM "john@example.com"');
// Search with date range
$dateRangeIds = $mailbox->searchMailbox('SINCE "1 Jan 2024" BEFORE "31 Jan 2024"');
// Search by subject
$subjectIds = $mailbox->searchMailbox('SUBJECT "Invoice"');
// Complex search combining criteria
$complexIds = $mailbox->searchMailbox('UNSEEN FROM "support@company.com" SUBJECT "Urgent"');
// Search from multiple senders (results are merged)
$multipleSendersIds = $mailbox->searchMailboxFrom(
'UNSEEN',
'sender1@example.com',
'sender2@example.com',
'sender3@example.com'
);
// Sort emails by criteria (SORTDATE, SORTFROM, SORTSUBJECT, SORTSIZE, etc.)
$sortedIds = $mailbox->sortMails(SORTARRIVAL, true, 'ALL'); // true = reverse order
if (empty($unseenMailsIds)) {
echo "No unseen messages found.\n";
} else {
echo "Found " . count($unseenMailsIds) . " unseen messages.\n";
}
} catch (Exception $ex) {
echo "Search failed: " . $ex->getMessage() . "\n";
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.