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 Setup

  1. Installation:

    composer require directorytree/imapengine-laravel
    

    Publish the config file:

    php artisan vendor:publish --provider="DirectoryTree\ImapEngine\ImapEngineServiceProvider"
    
  2. 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
    
  3. First Use Case: Fetch unread emails in the inbox:

    use DirectoryTree\ImapEngine\Mailbox;
    
    $mailbox = Mailbox::inbox();
    $messages = $mailbox->messages()->unread()->get();
    
  4. 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.

Implementation Patterns

Core Workflows

1. Fetching Messages

// Fetch all messages in the inbox
$messages = Mailbox::inbox()->messages()->get();

// Fetch unread messages with attachments
$messages = Mailbox::inbox()
    ->messages()
    ->unread()
    ->withAttachments()
    ->get();

2. Searching Messages

// 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();

3. Marking Messages as Read/Unread

// Mark a single message as read
$message->markAsRead();

// Mark all messages as read
Mailbox::inbox()->messages()->markAsRead();

4. Handling Attachments

foreach ($messages as $message) {
    foreach ($message->attachments as $attachment) {
        $attachment->saveTo(storage_path('app/attachments'));
    }
}

5. Real-Time Monitoring with imap:watch

# Start watching for new messages (long-polling)
php artisan imap:watch --mailbox=inbox --method=long-polling
  • Dispatches MailboxWatchAttemptsExceeded if idle fails repeatedly.

Integration Tips

Queue Jobs for Large Mailboxes

// Process messages in chunks to avoid timeouts
Mailbox::inbox()->messages()->chunk(100, function ($messages) {
    foreach ($messages as $message) {
        ProcessMessageJob::dispatch($message);
    }
});

Leverage Events

// Listen for new messages in a mailbox
event(new MailboxMessageAdded($mailbox, $message));

Custom Mailbox Handling

// Create a custom mailbox (e.g., "archive")
$archiveMailbox = Mailbox::create('archive');

Testing

Use ImapEngineTestCase from the package or mock Mailbox in tests:

$mailbox = Mockery::mock(Mailbox::class);
$mailbox->shouldReceive('messages')->andReturn($mockMessages);

Gotchas and Tips

Pitfalls

  1. Connection Timeouts:

    • IMAP operations can timeout if the server is slow. Use setTimeout() on the Mailbox:
      $mailbox->setTimeout(30); // 30 seconds
      
  2. Memory Limits:

    • Fetching large mailboxes can exhaust memory. Use chunk() or cursor():
      $messages = Mailbox::inbox()->messages()->cursor();
      
  3. SSL/TLS Issues:

    • Ensure IMAP_SSL is set correctly in .env. Some providers require IMAP_PORT=993 (SSL) or 143 (non-SSL).
  4. Rate Limiting:

    • Aggressive polling (e.g., imap:watch) may trigger rate limits. Use --method=long-polling or adjust --delay:
      php artisan imap:watch --delay=60
      
  5. Carbon Compatibility:

    • The package uses CarbonInterface, so ensure your app supports CarbonImmutable if needed.

Debugging

  1. Enable Verbose Logging:

    IMAPENGINE_LOG_LEVEL=debug
    

    Logs will appear in storage/logs/laravel.log.

  2. Check Connection Errors:

    • Wrap Mailbox operations in try-catch:
      try {
          $mailbox->connect();
      } catch (\DirectoryTree\ImapEngine\Exceptions\ConnectionException $e) {
          Log::error('IMAP connection failed: ' . $e->getMessage());
      }
      
  3. Validate Credentials:

    • Test credentials manually with a tool like Thunderbird or telnet:
      telnet imap.example.com 993
      

Extension Points

  1. Custom Message Processing:

    • Extend the Message class to add domain-specific methods:
      class CustomMessage extends \DirectoryTree\ImapEngine\Message
      {
          public function isInvoice()
          {
              return str_contains($this->subject, 'invoice');
          }
      }
      
  2. Override Default Mailbox Behavior:

    • Bind to the mailbox.created event to customize mailbox setup:
      Mailbox::created(function ($mailbox) {
          $mailbox->setFlag('\\Flagged', true); // Auto-flag new mailboxes
      });
      
  3. Add Custom Search Criteria:

    • Extend the MessageQueryBuilder:
      namespace App\Extensions;
      
      use DirectoryTree\ImapEngine\MessageQueryBuilder;
      
      class CustomMessageQueryBuilder extends MessageQueryBuilder
      {
          public function fromSender($sender)
          {
              return $this->where('from', $sender);
          }
      }
      
  4. Use with Laravel Notifications:

    • Trigger notifications when new messages arrive:
      event(new MailboxMessageAdded($mailbox, $message));
      // Listen in a Notification service
      

Configuration Quirks

  1. Default Mailbox Names:

    • The package uses standard IMAP mailbox names (INBOX, Sent, Trash). For custom names, use:
      Mailbox::named('custom-mailbox-name');
      
  2. Attachment Handling:

    • By default, attachments are streamed. For large files, use saveTo() with a temporary path:
      $attachment->saveTo(sys_get_temp_dir() . '/temp_attachment');
      
  3. Timezone Handling:

    • Ensure config/app.php timezone matches the IMAP server’s timezone to avoid date discrepancies.
  4. Fallback for Missing Extensions:

    • The package avoids PHP’s imap extension. If you encounter issues, verify no conflicting extensions are loaded.
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport