Installation
Run composer require bartv2/imap-bundle in your Laravel project (Symfony-based, but works via Laravel’s Symfony integration).
Ensure your composer.json includes "symfony/framework-bundle": "^6.4" or higher.
Publish Config Publish the default config:
php artisan vendor:publish --provider="Bartv2\ImapBundle\ImapBundle" --tag="config"
This creates config/packages/imap.yaml.
Configure Mailboxes
Edit imap.yaml with your IMAP server details (e.g., Gmail, custom IMAP provider):
imap:
mailboxes:
inbox:
host: "imap.example.com"
port: 993
username: "user@example.com"
password: "app_password" # Use an app-specific password for security
encryption: "ssl"
First Use Case: Fetch Emails
Inject the ImapEngine service into a controller or command:
use Bartv2\ImapBundle\Service\ImapEngine;
public function __construct(private ImapEngine $imapEngine) {}
public function fetchEmails()
{
$mailbox = $this->imapEngine->getMailbox('inbox');
$emails = $mailbox->getMessages(); // Returns a collection of messages
return response()->json($emails);
}
Mailbox Management
getMailbox('name')->connect() and disconnect() for explicit control.getMessages($limit, $offset) to avoid memory issues.$unread = $mailbox->search('UNSEEN');
$recent = $mailbox->search('SINCE "01-Jan-2024"');
Email Processing
foreach ($emails as $email) {
$headers = $email->getHeaders();
$body = $email->getBody();
$attachments = $email->getAttachments();
}
$mailbox->setFlags([1, 2, 3], 'SEEN'); // Mark messages 1, 2, 3 as read
Event-Driven Sync
scheduler to run periodic syncs (e.g., every 5 minutes):
// app/Console/Kernel.php
protected function schedule(Schedule $schedule)
{
$schedule->call(function () {
$this->imapEngine->syncMailbox('inbox');
})->everyFiveMinutes();
}
Integration with Laravel Mail
Mail facade for processing:
foreach ($emails as $email) {
Mail::raw($email->getBody(), function ($message) use ($email) {
$message->to('recipient@example.com')
->subject($email->getHeader('Subject'));
});
}
foreach ($emails as $email) {
ProcessEmail::dispatch($email);
}
try {
$mailbox->connect();
} catch (ImapException $e) {
throw new RetryException($e, 3); // Retry 3 times
}
Authentication Failures
config('imap.mailboxes.inbox.password')) and generate app-specific passwords for providers like Gmail.SSL/TLS Validation
validate_cert: false disables certificate validation, which is insecure. Some providers (e.g., self-signed certs) may require this.proxy:
ca_bundle: "/path/to/cert.pem"
Connection Timeouts
timeout in config or implement retry logic:
timeout: 60 # Increase to 60 seconds
Memory Leaks
getMessages($limit) and paginate results.IMAP Server Quirks
"login" vs "plain").debug: true in config and check server documentation.Enable Debug Mode:
debug: true
Logs IMAP commands/responses to storage/logs/imap.log.
Check Connection Status:
if (!$mailbox->isConnected()) {
$mailbox->connect();
}
Handle Exceptions:
Catch Bartv2\ImapBundle\Exception\ImapException for connection/parsing errors.
Custom Message Parsing
Extend the Message class to add domain-specific logic:
namespace App\Services;
use Bartv2\ImapBundle\Model\Message as BaseMessage;
class CustomMessage extends BaseMessage
{
public function isPromotional(): bool
{
return str_contains($this->getHeader('Subject'), 'Promo');
}
}
Register the binding in a service provider:
$this->app->bind(
\Bartv2\ImapBundle\Model\Message::class,
App\Services\CustomMessage::class
);
Proxy Support Configure proxies for corporate environments:
proxy:
socket: "tcp://proxy.example.com:8080"
username: "proxy_user"
password: "proxy_pass"
Laravel Notifications Trigger notifications from parsed emails:
if ($email->isPromotional()) {
Notification::send($user, new PromotionalEmail($email));
}
Testing
Use Laravel’s Mockery to simulate IMAP responses in tests:
$mailbox = $this->app->make('imap.mailbox.inbox');
$mailbox->shouldReceive('getMessages')
->andReturn([new CustomMessage()]);
How can I help you explore Laravel packages today?