directorytree/imapengine-laravel
Laravel integration for ImapEngine, a PHP IMAP client that manages mailboxes without the PHP imap extension. Configure connections, access mailboxes and messages, and use a clean API to work with IMAP servers in your Laravel apps.
Installation:
composer require directorytree/imapengine-laravel
Publish the config file:
php artisan vendor:publish --provider="DirectoryTree\ImapEngine\ImapEngineServiceProvider"
Configuration:
Edit .env with IMAP credentials:
IMAP_HOST=imap.example.com
IMAP_PORT=993
IMAP_USERNAME=user@example.com
IMAP_PASSWORD=yourpassword
IMAP_SSL=true
First Use Case: Fetch unread emails in the inbox:
use DirectoryTree\ImapEngine\Mailbox;
$mailbox = Mailbox::inbox();
$messages = $mailbox->messages()->unread()->get();
Key Classes:
Mailbox: Represents an IMAP mailbox (e.g., Mailbox::inbox()).Message: Represents an email (e.g., $message->subject, $message->body).MessageCollection: Handles collections of messages.// Fetch all messages in the inbox
$messages = Mailbox::inbox()->messages()->get();
// Fetch unread messages with attachments
$messages = Mailbox::inbox()
->messages()
->unread()
->withAttachments()
->get();
// Search by subject
$messages = Mailbox::inbox()
->messages()
->search('subject', 'invoice')
->get();
// Search by date range (Carbon instances)
$messages = Mailbox::inbox()
->messages()
->since(now()->subDays(7))
->get();
// Mark a single message as read
$message->markAsRead();
// Mark all messages as read
Mailbox::inbox()->messages()->markAsRead();
foreach ($messages as $message) {
foreach ($message->attachments as $attachment) {
$attachment->saveTo(storage_path('app/attachments'));
}
}
imap:watch# Start watching for new messages (long-polling)
php artisan imap:watch --mailbox=inbox --method=long-polling
MailboxWatchAttemptsExceeded if idle fails repeatedly.// Process messages in chunks to avoid timeouts
Mailbox::inbox()->messages()->chunk(100, function ($messages) {
foreach ($messages as $message) {
ProcessMessageJob::dispatch($message);
}
});
// Listen for new messages in a mailbox
event(new MailboxMessageAdded($mailbox, $message));
// Create a custom mailbox (e.g., "archive")
$archiveMailbox = Mailbox::create('archive');
Use ImapEngineTestCase from the package or mock Mailbox in tests:
$mailbox = Mockery::mock(Mailbox::class);
$mailbox->shouldReceive('messages')->andReturn($mockMessages);
Connection Timeouts:
setTimeout() on the Mailbox:
$mailbox->setTimeout(30); // 30 seconds
Memory Limits:
chunk() or cursor():
$messages = Mailbox::inbox()->messages()->cursor();
SSL/TLS Issues:
IMAP_SSL is set correctly in .env. Some providers require IMAP_PORT=993 (SSL) or 143 (non-SSL).Rate Limiting:
imap:watch) may trigger rate limits. Use --method=long-polling or adjust --delay:
php artisan imap:watch --delay=60
Carbon Compatibility:
CarbonInterface, so ensure your app supports CarbonImmutable if needed.Enable Verbose Logging:
IMAPENGINE_LOG_LEVEL=debug
Logs will appear in storage/logs/laravel.log.
Check Connection Errors:
Mailbox operations in try-catch:
try {
$mailbox->connect();
} catch (\DirectoryTree\ImapEngine\Exceptions\ConnectionException $e) {
Log::error('IMAP connection failed: ' . $e->getMessage());
}
Validate Credentials:
telnet:
telnet imap.example.com 993
Custom Message Processing:
Message class to add domain-specific methods:
class CustomMessage extends \DirectoryTree\ImapEngine\Message
{
public function isInvoice()
{
return str_contains($this->subject, 'invoice');
}
}
Override Default Mailbox Behavior:
mailbox.created event to customize mailbox setup:
Mailbox::created(function ($mailbox) {
$mailbox->setFlag('\\Flagged', true); // Auto-flag new mailboxes
});
Add Custom Search Criteria:
MessageQueryBuilder:
namespace App\Extensions;
use DirectoryTree\ImapEngine\MessageQueryBuilder;
class CustomMessageQueryBuilder extends MessageQueryBuilder
{
public function fromSender($sender)
{
return $this->where('from', $sender);
}
}
Use with Laravel Notifications:
event(new MailboxMessageAdded($mailbox, $message));
// Listen in a Notification service
Default Mailbox Names:
INBOX, Sent, Trash). For custom names, use:
Mailbox::named('custom-mailbox-name');
Attachment Handling:
saveTo() with a temporary path:
$attachment->saveTo(sys_get_temp_dir() . '/temp_attachment');
Timezone Handling:
config/app.php timezone matches the IMAP server’s timezone to avoid date discrepancies.Fallback for Missing Extensions:
imap extension. If you encounter issues, verify no conflicting extensions are loaded.How can I help you explore Laravel packages today?