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

Php Imap Laravel Package

webklex/php-imap

PHP-IMAP is a pure-PHP IMAP client wrapper that works without the php-imap extension, supporting IMAP IDLE and OAuth auth. Optionally use php-imap for better decoding, edge cases, and legacy POP3 support.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require webklex/php-imap

For Laravel, use the dedicated wrapper:

composer require webklex/laravel-imap
  1. Configuration: Create a config file (e.g., config/imap.php) with your IMAP server details:

    return [
        'default' => [
            'host' => env('IMAP_HOST', 'imap.example.com'),
            'port' => env('IMAP_PORT', 993),
            'encryption' => env('IMAP_ENCRYPTION', 'ssl'),
            'validate_cert' => env('IMAP_VALIDATE_CERT', false),
            'username' => env('IMAP_USERNAME'),
            'password' => env('IMAP_PASSWORD'),
            'protocol' => env('IMAP_PROTOCOL', 'imap'),
            'path_prefix' => env('IMAP_PATH_PREFIX', ''),
        ],
    ];
    
  2. First Use Case: Fetch and display unread emails from the INBOX:

    use Webklex\PHPIMAP\ClientManager;
    
    $clientManager = new ClientManager('config/imap.php');
    $client = $clientManager->account('default');
    
    $client->connect();
    $unreadMessages = $client->getFolder('INBOX')
        ->messages()
        ->whereFlag('\\Seen', false)
        ->get();
    
    foreach ($unreadMessages as $message) {
        echo $message->getSubject() . "\n";
    }
    

Key Entry Points

  • ClientManager: Manages multiple IMAP accounts/configurations.
  • Client: Handles connection and folder operations.
  • Folder: Represents an IMAP folder (e.g., INBOX, Sent).
  • Message: Represents an email with methods for parsing, attachments, and actions.

Implementation Patterns

Common Workflows

1. Connecting and Fetching Emails

$client = $clientManager->account('default');
$client->connect(); // Establish connection

// Fetch all messages from a folder with pagination
$messages = $client->getFolder('INBOX')
    ->messages()
    ->paginate(10, 1); // 10 items, page 1

foreach ($messages as $message) {
    echo $message->getSubject() . "\n";
}

2. Searching Messages

Use query builders for complex searches:

// Find unread messages from a specific sender
$messages = $client->getFolder('INBOX')
    ->messages()
    ->whereFlag('\\Seen', false)
    ->whereFrom('sender@example.com')
    ->get();

// Search using custom criteria (e.g., subject contains "invoice")
$messages = $client->getFolder('INBOX')
    ->messages()
    ->search('SUBJECT "invoice"')
    ->get();

3. Handling Attachments

foreach ($messages as $message) {
    $attachments = $message->getAttachments();
    foreach ($attachments as $attachment) {
        $path = $attachment->saveTo(storage_path('app/attachments'));
        echo "Saved: " . $path . "\n";
    }
}

4. Moving/Copying Messages

$message->move('INBOX.Archived'); // Move to a folder
$message->copy('INBOX.Backup');  // Copy to another folder

5. IMAP IDLE (Real-Time Updates)

$client->idle(function ($message) {
    echo "New message arrived: " . $message->getSubject() . "\n";
});

6. OAuth Authentication

Configure OAuth in your IMAP settings and use the oauth protocol:

$client->setConfig([
    'protocol' => 'oauth',
    'oauth_token' => 'your_oauth_token',
]);
$client->connect();

Integration Tips

Laravel Integration

  • Use the webklex/laravel-imap package for seamless Laravel integration:
    use Webklex\IMAP\Facades\IMAP;
    
    $messages = IMAP::account('default')->getFolder('INBOX')->messages()->get();
    
  • Bind the package to Laravel's service container in config/app.php:
    'providers' => [
        Webklex\IMAP\IMAPServiceProvider::class,
    ],
    

Queueing Long-Running Tasks

Offload heavy IMAP operations (e.g., processing thousands of emails) to Laravel queues:

dispatch(new ProcessEmailsJob($client, 'INBOX'));

Caching

Cache folder/message data to reduce IMAP server load:

$cacheKey = 'imap_messages_' . md5('INBOX');
$messages = Cache::remember($cacheKey, now()->addHours(1), function () use ($client) {
    return $client->getFolder('INBOX')->messages()->get();
});

Error Handling

Wrap IMAP operations in try-catch blocks:

try {
    $client->connect();
    $messages = $client->getFolder('INBOX')->messages()->get();
} catch (\Webklex\PHPIMAP\Exceptions\ConnectionException $e) {
    Log::error('IMAP Connection Failed: ' . $e->getMessage());
    // Retry logic or fallback
}

Gotchas and Tips

Pitfalls

1. Connection Timeouts

  • Issue: IMAP operations may hang or timeout, especially with large folders.
  • Fix: Set a timeout in the config:
    'timeout' => 30, // seconds
    
  • Workaround: Use smaller batch sizes for fetching messages.

2. Character Encoding Issues

  • Issue: Non-UTF-8 emails (e.g., from Asian or Russian senders) may display incorrectly.
  • Fix: Configure the decoder in your imap.php:
    'decoder' => [
        'charset' => 'utf-8',
        'iconv_options' => ['//IGNORE'],
    ],
    
  • Tip: Use Message::getRawBody() to inspect raw content if parsing fails.

3. Folder Path Delimiters

  • Issue: Folder paths with special characters (e.g., INBOX/Special Folder) may break.
  • Fix: Escape paths or use path_prefix in config:
    'path_prefix' => 'INBOX/',
    

4. IMAP IDLE Quirks

  • Issue: IDLE may not work with all IMAP servers (e.g., Gmail requires specific settings).
  • Fix: Test IDLE with a simple script first:
    $client->idle(function ($message) {
        echo "New message: " . $message->getSubject() . "\n";
    }, 60); // Timeout after 60 seconds
    
  • Tip: Use IMAP::FT_PEEK to avoid marking messages as seen during IDLE.

5. Attachment Handling

  • Issue: Large attachments may cause memory issues or timeouts.
  • Fix: Stream attachments directly to storage:
    $attachment->saveTo(storage_path('app/attachments'), true); // Stream to disk
    

6. Date Parsing Errors

  • Issue: Messages with malformed dates may throw exceptions.
  • Fix: Extend the date formats in config:
    'date_formats' => [
        'Y-m-d H:i:s',
        'D, d M Y H:i:s O',
        // Add custom formats if needed
    ],
    

7. Legacy Protocols

  • Issue: POP3 or legacy IMAP protocols may not work without php-imap extension.
  • Fix: Enable the php-imap extension or use the legacy-imap protocol:
    'protocol' => 'legacy-imap',
    

Debugging Tips

1. Enable Debugging

$client->setDebug(true);
$client->connect();

Check logs for raw IMAP commands/responses.

2. Inspect Raw Messages

$rawBody = $message->getRawBody();
file_put_contents('debug.eml', $rawBody); // Save to file for inspection

3. Use Masks for Selective Data

Masks allow fetching only specific parts of a message to reduce load:

$messages = $client->getFolder('INBOX')
    ->messages()
    ->mask(['subject', 'from', 'date']) // Only fetch
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor