Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Imap Laravel Package

webklex/laravel-imap

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require webklex/laravel-imap
    php artisan vendor:publish --provider="Webklex\IMAP\IMAPServiceProvider"
    

    Configure .env with IMAP credentials:

    IMAP_HOST=smtp.example.com
    IMAP_PORT=993
    IMAP_ENCRYPTION=ssl
    IMAP_USERNAME=user@example.com
    IMAP_PASSWORD=yourpassword
    
  2. First Use Case: Fetch unread emails in a controller:

    use Webklex\IMAP\ClientManager;
    
    public function fetchUnreadEmails()
    {
        $client = app(ClientManager::class)->client();
        $emails = $client->getMailbox('INBOX')->search(['UNSEEN']);
    
        return view('emails.index', compact('emails'));
    }
    
  3. Key Files to Review:

    • config/imap.php (default settings)
    • app/Providers/IMAPServiceProvider.php (customization)
    • Official Docs (API reference)

Implementation Patterns

Core Workflows

  1. Email Fetching & Processing:

    // Fetch all emails in a mailbox
    $mailbox = $client->getMailbox('INBOX');
    $emails = $mailbox->getEmails(['BODY[]', 'FROM', 'SUBJECT']);
    
    // Process each email
    foreach ($emails as $email) {
        $body = $email->getBody();
        $from = $email->getFrom();
        // Parse/Store logic...
    }
    
  2. Real-Time Listeners:

    // Listen for new emails (requires IMAP IDLE support)
    $client->listen(function ($mailbox, $email) {
        // Handle new email (e.g., trigger a job)
        dispatch(new ProcessEmailJob($email));
    });
    
  3. Attachment Handling:

    $attachments = $email->getAttachments();
    foreach ($attachments as $attachment) {
        Storage::put('attachments/' . $attachment->getFilename(), $attachment->getContent());
    }
    
  4. Search & Filtering:

    // Search for emails with attachments
    $emails = $mailbox->search(['HAVE', 'attachment']);
    
    // Search by date range
    $emails = $mailbox->search([
        'SINCE', '01-Jan-2023',
        'BEFORE', '01-Feb-2023'
    ]);
    

Integration Tips

  • Queue Processing: Offload email processing to queues to avoid timeouts:
    foreach ($emails as $email) {
        ProcessEmail::dispatch($email)->onQueue('emails');
    }
    
  • Rate Limiting: Use Laravel’s throttle middleware for API endpoints triggered by IMAP events.
  • Logging: Log IMAP operations for debugging:
    $client->setLogger(app(\Monolog\Logger::class));
    
  • Testing: Use the Webklex\IMAP\Testing\TestIMAP trait for unit tests:
    use Webklex\IMAP\Testing\TestIMAP;
    
    public function testEmailFetching()
    {
        $this->actingAsIMAPUser();
        // Assertions...
    }
    

Gotchas and Tips

Common Pitfalls

  1. Connection Issues:

    • Symptom: imap_open() fails silently.
    • Fix: Verify .env credentials and ensure the PHP imap extension is enabled (php -m | grep imap).
    • Debug: Enable verbose logging in config/imap.php:
      'log' => [
          'enabled' => true,
          'path' => storage_path('logs/imap.log'),
      ],
      
  2. Memory Limits:

    • Symptom: Allowed memory size exhausted when fetching large mailboxes.
    • Fix: Fetch emails in batches or use getEmails(['UID']) to fetch only UIDs first, then load bodies separately.
  3. Timezone Mismatches:

    • Symptom: Email dates appear incorrect.
    • Fix: Set the IMAP client’s timezone in config/imap.php:
      'timezone' => 'America/New_York',
      
  4. IMAP Server Quirks:

    • Symptom: Search queries return unexpected results.
    • Fix: Test queries in a tool like Thunderbird first. Use imap_last_error() for debugging:
      $client->getMailbox('INBOX')->search(['UNSEEN']);
      error_log(imap_last_error());
      

Debugging Tips

  • Enable IMAP Debugging:
    $client->setDebug(true); // Logs raw IMAP commands/responses
    
  • Check IMAP Server Capabilities:
    $capabilities = $client->getCapabilities();
    // Verify 'IDLE' is supported for real-time listening.
    
  • Handle IMAP Errors Gracefully:
    try {
        $emails = $mailbox->getEmails();
    } catch (\Webklex\IMAP\Exceptions\ConnectionException $e) {
        // Retry or notify admin
    }
    

Extension Points

  1. Custom Mailbox Classes: Extend \Webklex\IMAP\Mailbox to add domain-specific methods:

    class CustomMailbox extends \Webklex\IMAP\Mailbox
    {
        public function getSupportTickets()
        {
            return $this->search(['SUBJECT', 'ticket:']);
        }
    }
    

    Bind it in IMAPServiceProvider:

    $this->app->bind(\Webklex\IMAP\Mailbox::class, function ($app) {
        return new CustomMailbox($app->make(\Webklex\IMAP\Client::class));
    });
    
  2. Event Listeners: Subscribe to IMAP events (e.g., imap.message.fetched):

    // In EventServiceProvider
    public function boot()
    {
        event(new \Webklex\IMAP\Events\MessageFetched($email));
    }
    
  3. Custom IMAP Commands: Use the low-level rawCommand() method for unsupported IMAP extensions:

    $response = $client->rawCommand('UID SEARCH CHANGEDSINCE "01-Jan-2023"');
    
  4. Mocking for Tests: Use the Webklex\IMAP\Testing\FakeIMAP class to simulate IMAP responses:

    $fakeImap = new FakeIMAP();
    $fakeImap->shouldReceive('getMailbox')->andReturnSelf();
    $fakeImap->shouldReceive('search')->andReturn([1, 2, 3]);
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours