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 Package

directorytree/imapengine

IMAPEngine is a Laravel-friendly PHP package for working with IMAP mailboxes. Connect to servers, list folders, fetch messages and attachments, search and manage mail, and handle common IMAP operations through a clean, high-level API.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer require directorytree/imapengine
    
  2. Basic Connection:
    use DirectoryTree\ImapEngine\Connection;
    use DirectoryTree\ImapEngine\Folder;
    
    $connection = new Connection('imap.example.com', [
        'ssl' => true,
        'username' => 'user@example.com',
        'password' => 'password',
    ]);
    
    $inbox = $connection->getFolder('INBOX');
    
  3. First Use Case: Fetch unread emails with lazy-loaded headers (reduces bandwidth):
    $messages = $inbox->query()
        ->whereUnread()
        ->withLazyHeaders()
        ->get();
    
    foreach ($messages as $message) {
        echo $message->subject . "\n";
    }
    

Where to Look First

  • Usage Guide: Start with the "Messages" and "Querying" sections.
  • Laravel Integration: Check the HasParsedMessage trait for Eloquent model hydration.
  • Examples: Browse the tests for real-world patterns (e.g., bulk operations, attachments).

Implementation Patterns

Core Workflows

1. Fetching Messages

  • Lazy Loading: Reduce memory/bandwidth by loading headers/attachments on-demand:
    $messages = $folder->query()
        ->withLazyHeaders() // Load headers only when accessed
        ->withLazyAttachments() // Load attachments only when needed
        ->get();
    
  • Bulk Fetching: Fetch by UID range for performance:
    $messages = $folder->fetchByUidRange(1000, 2000);
    

2. Querying

  • Server-Side Sorting: Offload sorting to IMAP server:
    $messages = $folder->query()
        ->sortByDate('desc')
        ->get();
    
  • Complex Criteria:
    $messages = $folder->query()
        ->whereFrom('sender@example.com')
        ->whereLargerThan(1024 * 1024) // >1MB
        ->whereSentSince(now()->subDays(7))
        ->get();
    

3. Bulk Operations

  • Flag/Delete in Batches:
    $folder->bulkQuery()
        ->whereUnread()
        ->flag(\DirectoryTree\ImapEngine\Flag::Seen)
        ->execute();
    

4. Real-Time Updates

  • Long Polling:
    $folder->poll(function (Folder $folder) {
        $newMessages = $folder->query()->whereUnseen()->get();
        // Process new messages
    }, 30); // Check every 30 seconds
    
  • IDLE Mode (for persistent connections):
    $folder->idle(function (Folder $folder) {
        // Handle new messages in real-time
    });
    

5. Attachment Handling

  • Extract Attachments:
    foreach ($message->attachments() as $attachment) {
        $attachment->saveTo(storage_path('app/attachments/' . $attachment->name));
    }
    
  • Content-Disposition Awareness:
    if ($attachment->contentDisposition === 'attachment') {
        // Handle as downloadable file
    }
    

Laravel Integration Tips

Service Provider Setup

// app/Providers/ImapServiceProvider.php
public function register()
{
    $this->app->singleton(Connection::class, function ($app) {
        return new Connection(config('imap.host'), [
            'ssl' => config('imap.ssl'),
            'username' => config('imap.username'),
            'password' => config('imap.password'),
        ]);
    });
}

Eloquent Model Hydration

// app/Models/Email.php
use DirectoryTree\ImapEngine\HasParsedMessage;

class Email extends Model
{
    use HasParsedMessage;

    protected $fillable = ['subject', 'body', 'from', 'to', 'uid', 'folder'];

    public static function fromImapMessage(Message $message, Folder $folder)
    {
        return static::create([
            'subject' => $message->subject,
            'body' => $message->text,
            'from' => $message->from->address,
            'to' => $message->to->address,
            'uid' => $message->uid,
            'folder' => $folder->name,
        ]);
    }
}

Artisan Command for Syncing

// app/Console/Commands/SyncEmails.php
public function handle()
{
    $connection = app(Connection::class);
    $folder = $connection->getFolder('INBOX');

    $messages = $folder->query()
        ->whereUnread()
        ->get();

    foreach ($messages as $message) {
        Email::fromImapMessage($message, $folder);
    }
}

Event Listeners for Real-Time

// app/Listeners/ProcessNewEmail.php
public function handle($event)
{
    $message = $event->message;
    // Process or dispatch further actions
}

Gotchas and Tips

Pitfalls and Debugging

1. Connection Issues

  • Symptom: ImapConnectionFailedException with no clear cause.
  • Fix: Enable debug mode and check for stream socket warnings:
    $connection = new Connection('imap.example.com', [
        'ssl' => true,
        'debug' => true, // Enable debug output
    ]);
    
  • Common Causes:
    • Firewall/Proxy: Ensure outbound IMAP (port 993 for SSL) is allowed.
    • Server Certificates: Use verifyPeer => false only for testing (insecure!).
    • Authentication: Some providers (e.g., Gmail) require authMechanism => 'XOAUTH2'.

2. Lazy Loading Quirks

  • Issue: Headers/attachments not loading as expected.
  • Debug:
    if ($message->hasLazyHeaders()) {
        $message->loadHeaders(); // Force load
    }
    
  • Fix: Ensure withLazyHeaders()/withLazyAttachments() are explicitly called in queries.

3. UID vs. Sequence Numbers

  • Gotcha: Mixing UIDs and sequence numbers can cause inconsistencies.
  • Tip: Always use UIDs for reliable message identification:
    $message = $folder->fetchByUid(1234);
    

4. Multi-Line Responses

  • Issue: Malformed IMAP responses (e.g., from older servers).
  • Fix: Upgrade to v1.18.1+, which includes fixes for multi-line parsing.

5. Attachment Corruption

  • Symptom: Attachments fail to save or are corrupted.
  • Debug:
    $attachment->content; // Check raw content
    $attachment->contentType; // Verify MIME type
    
  • Fix: Ensure Content-Disposition is parsed correctly (added in v1.17.3).

6. Date Handling

  • Issue: Incorrect dates in messages.
  • Fix: Use Carbon for consistency:
    $date = $message->date->toDateTime(); // Convert to Carbon
    

7. Bulk Operations Failures

  • Symptom: bulkQuery() throws errors on large datasets.
  • Tip: Batch operations in chunks:
    $folder->bulkQuery()
        ->whereUnread()
        ->limit(100) // Process 100 at a time
        ->flag(\Flag::Seen)
        ->execute();
    

Configuration Quirks

SSL/TLS Settings

  • Gmail Example:
    $connection = new Connection('imap.gmail.com', [
        'ssl' => true,
        'port' => 993,
        'authMechanism' => 'XOAUTH2', // For OAuth2
        'oauthUser' => 'user@example.com',
        'oauthToken' => 'your_oauth_token',
    ]);
    

Timeouts

  • Default: 30 seconds for most operations.
  • Override:
    $connection = new Connection('imap.example.com', [
        'timeout' => 60, // 60 seconds
    ]);
    

Character Encoding

  • Issue: Non-UTF-8 emails (e.g., Russian, Japanese).
  • Fix: Force encoding in queries:
    $messages = $folder->query()
        ->withCharset('utf-8')
        ->get();
    

Extension Points

1. Custom Message Parsing

  • Extend `DirectoryTree
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.
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
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope