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

Imapengine Laravel Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require directorytree/imapengine-laravel
    php artisan vendor:publish --provider="DirectoryTree\ImapEngine\ImapEngineServiceProvider"
    
  2. Configure IMAP Credentials: Add to .env:

    IMAP_HOST=imap.example.com
    IMAP_PORT=993
    IMAP_USERNAME=user@example.com
    IMAP_PASSWORD=yourpassword
    IMAP_SSL=true
    
  3. First Command: Test connection with:

    php artisan imap:watch --mailbox=INBOX --method=idle
    
  4. Basic Usage in Code:

    use DirectoryTree\ImapEngine\Facades\ImapEngine;
    
    $mailbox = ImapEngine::mailbox('INBOX');
    $messages = $mailbox->messages()->unread()->limit(10)->get();
    

Where to Look First

  • Config File: config/imap.php – Centralize IMAP settings (host, credentials, timeouts).
  • Artisan Commands: php artisan list → Look for imap:* commands (e.g., imap:watch).
  • Events: MailboxSynced, MailboxWatchAttemptsExceeded – Hook into these for reactivity.
  • Facade: ImapEngine – Primary entry point for mailbox operations.

First Use Case: Fetch and Process Emails

// Fetch unread emails from INBOX
$unreadEmails = ImapEngine::mailbox('INBOX')
    ->messages()
    ->unread()
    ->limit(50)
    ->get();

// Process each email (e.g., store in DB or dispatch jobs)
foreach ($unreadEmails as $email) {
    ProcessEmail::dispatch($email);
}

Implementation Patterns

1. Mailbox Management

Fetching Messages

// Get all messages in a mailbox
$messages = ImapEngine::mailbox('INBOX')->messages()->get();

// Filter by flags (e.g., unread, seen)
$unread = ImapEngine::mailbox('INBOX')->messages()->unread()->get();

// Limit results
$recent = ImapEngine::mailbox('INBOX')->messages()->limit(10)->get();

Searching Messages

// Search by subject
$messages = ImapEngine::mailbox('INBOX')
    ->messages()
    ->where('subject', 'like', '%invoice%')
    ->get();

// Search by sender
$messages = ImapEngine::mailbox('INBOX')
    ->messages()
    ->from('support@example.com')
    ->get();

2. Real-Time Monitoring with imap:watch

Basic Watcher Setup

php artisan imap:watch --mailbox=INBOX --method=idle
  • --method: Use idle (low-resource) or long-polling (fallback for restrictive environments).
  • Schedule in app/Console/Kernel.php:
    $schedule->command('imap:watch --mailbox=INBOX --method=idle')->everyMinute();
    

Handling Events

Listen for MailboxSynced to react to new emails:

use DirectoryTree\ImapEngine\Events\MailboxSynced;

public function handle(MailboxSynced $event) {
    foreach ($event->emails as $email) {
        // Process new email (e.g., store in DB, send notification)
        NewEmailReceived::dispatch($email);
    }
}

3. Asynchronous Processing

Combine with Laravel Queues for background processing:

// In your event listener
public function handle(MailboxSynced $event) {
    foreach ($event->emails as $email) {
        ProcessEmailJob::dispatch($email);
    }
}

Define the job:

class ProcessEmailJob implements ShouldQueue {
    public function handle() {
        // Parse email, store attachments, etc.
    }
}

4. Custom Mailbox Operations

Create a Custom Mailbox Class

use DirectoryTree\ImapEngine\Mailbox;

class SupportMailbox extends Mailbox {
    public function __construct() {
        parent::__construct('Support');
    }

    public function getTickets() {
        return $this->messages()
            ->where('subject', 'like', '%ticket%')
            ->orderBy('date', 'desc')
            ->get();
    }
}

Register in AppServiceProvider:

$this->app->bind(SupportMailbox::class, function () {
    return new SupportMailbox();
});

Usage:

$tickets = app(SupportMailbox::class)->getTickets();

5. Error Handling and Retries

Handle MailboxWatchAttemptsExceeded:

use DirectoryTree\ImapEngine\Events\MailboxWatchAttemptsExceeded;

public function handle(MailboxWatchAttemptsExceeded $event) {
    Log::error("Failed to watch mailbox {$event->mailbox} after {$event->attempts} attempts.");
    // Optionally: Notify admin or switch to long-polling
}

6. Testing IMAP Interactions

Use imapengine's test utilities or mock the facade:

// Example using Mockery
$mailboxMock = Mockery::mock(Mailbox::class);
$mailboxMock->shouldReceive('messages')
    ->andReturnSelf();
$mailboxMock->shouldReceive('unread')
    ->andReturnSelf();
$mailboxMock->shouldReceive('get')
    ->andReturn([new Message()]);

$mailboxMock->makePartial();

Gotchas and Tips

Pitfalls

  1. Connection Timeouts:

    • IMAP servers may drop idle connections. Use long-polling as a fallback:
      php artisan imap:watch --mailbox=INBOX --method=long-polling --interval=30
      
  2. Credential Exposure:

    • Never hardcode credentials. Use Laravel’s .env or a secrets manager (e.g., Vault).
    • Avoid logging IMAP passwords or sensitive data.
  3. Rate Limiting:

    • Aggressive polling (e.g., every few seconds) can trigger IMAP server bans. Start with longer intervals (e.g., 30–60 seconds).
  4. Email Parsing Limits:

    • Complex emails (e.g., large attachments, nested HTML) may fail to parse. Use try-catch:
      try {
          $body = $email->body();
      } catch (\Exception $e) {
          Log::error("Failed to parse email body: " . $e->getMessage());
      }
      
  5. Time Zone Issues:

    • IMAP servers may return timestamps in UTC. Normalize with Carbon:
      $localDate = $email->date->setTimezone('America/New_York');
      
  6. Message ID Collisions:

    • IMAP message_id may not be unique across mailboxes. Use a composite key (e.g., mailbox + message_id) in your database.

Debugging Tips

  1. Enable Verbose Logging: Add to config/imap.php:

    'debug' => env('IMAP_DEBUG', false),
    
  2. Check IMAP Server Logs:

    • For self-hosted servers (e.g., Dovecot), inspect logs for connection issues:
      tail -f /var/log/mail.log
      
  3. Test with a Dummy Mailbox:

    • Use a test mailbox (e.g., TestMailbox) to avoid affecting production data during development.
  4. Use Spatie Ray:

    • Install spatie/laravel-ray to inspect IMAP operations in real-time:
      composer require spatie/laravel-ray
      
  5. Validate IMAP Credentials:

    • Manually test credentials with imap_open:
      $connection = imap_open(
          "{imap.example.com:993/imap/ssl}INBOX",
          "user@example.com",
          "password"
      );
      if (!$connection) {
          die("IMAP connection failed: " . imap_last_error());
      }
      

Configuration Quirks

  1. SSL/TLS Settings:

    • Ensure IMAP_SSL is true for secure connections. For STARTTLS, use:
      IMAP_PORT=143
      IMAP_SSL=false
      IMAP_STARTTLS=true
      
  2. Port Conflicts:

    • If using multiple mailboxes, ensure ports are not blocked or exhausted. Limit concurrent connections:
      ImapEngine::setMaxConnections(5); // Default is 10
      
  3. Character Encoding:

    • IMAP may return non-UTF-8 emails. Normalize with:
      $subject = mb_convert_
      
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata