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

Imap Bundle Laravel Package

bartv2/imap-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Run composer require bartv2/imap-bundle in your Laravel project (Symfony-based, but works via Laravel’s Symfony integration). Ensure your composer.json includes "symfony/framework-bundle": "^6.4" or higher.

  2. Publish Config Publish the default config:

    php artisan vendor:publish --provider="Bartv2\ImapBundle\ImapBundle" --tag="config"
    

    This creates config/packages/imap.yaml.

  3. Configure Mailboxes Edit imap.yaml with your IMAP server details (e.g., Gmail, custom IMAP provider):

    imap:
        mailboxes:
            inbox:
                host: "imap.example.com"
                port: 993
                username: "user@example.com"
                password: "app_password"  # Use an app-specific password for security
                encryption: "ssl"
    
  4. First Use Case: Fetch Emails Inject the ImapEngine service into a controller or command:

    use Bartv2\ImapBundle\Service\ImapEngine;
    
    public function __construct(private ImapEngine $imapEngine) {}
    
    public function fetchEmails()
    {
        $mailbox = $this->imapEngine->getMailbox('inbox');
        $emails = $mailbox->getMessages(); // Returns a collection of messages
        return response()->json($emails);
    }
    

Implementation Patterns

Core Workflows

  1. Mailbox Management

    • Connect/Disconnect: Use getMailbox('name')->connect() and disconnect() for explicit control.
    • Batch Operations: Fetch messages in batches with getMessages($limit, $offset) to avoid memory issues.
    • Searching: Filter emails by criteria (e.g., unread, date range):
      $unread = $mailbox->search('UNSEEN');
      $recent = $mailbox->search('SINCE "01-Jan-2024"');
      
  2. Email Processing

    • Parse Messages: Extract headers, body, and attachments:
      foreach ($emails as $email) {
          $headers = $email->getHeaders();
          $body = $email->getBody();
          $attachments = $email->getAttachments();
      }
      
    • Mark as Read: Update message flags:
      $mailbox->setFlags([1, 2, 3], 'SEEN'); // Mark messages 1, 2, 3 as read
      
  3. Event-Driven Sync

    • Use Laravel’s scheduler to run periodic syncs (e.g., every 5 minutes):
      // app/Console/Kernel.php
      protected function schedule(Schedule $schedule)
      {
          $schedule->call(function () {
              $this->imapEngine->syncMailbox('inbox');
          })->everyFiveMinutes();
      }
      
  4. Integration with Laravel Mail

    • Forward incoming emails to Laravel’s Mail facade for processing:
      foreach ($emails as $email) {
          Mail::raw($email->getBody(), function ($message) use ($email) {
              $message->to('recipient@example.com')
                      ->subject($email->getHeader('Subject'));
          });
      }
      

Advanced Patterns

  • Queue Processing: Offload email processing to queues to avoid timeouts:
    foreach ($emails as $email) {
        ProcessEmail::dispatch($email);
    }
    
  • Rate Limiting: Implement retries with exponential backoff for failed connections:
    try {
        $mailbox->connect();
    } catch (ImapException $e) {
        throw new RetryException($e, 3); // Retry 3 times
    }
    

Gotchas and Tips

Pitfalls

  1. Authentication Failures

    • Issue: Hardcoded passwords in config or using weak passwords (e.g., Gmail’s "password" instead of an app-specific password).
    • Fix: Use environment variables (config('imap.mailboxes.inbox.password')) and generate app-specific passwords for providers like Gmail.
  2. SSL/TLS Validation

    • Issue: validate_cert: false disables certificate validation, which is insecure. Some providers (e.g., self-signed certs) may require this.
    • Fix: Use a valid certificate or configure CA bundles:
      proxy:
          ca_bundle: "/path/to/cert.pem"
      
  3. Connection Timeouts

    • Issue: Default timeout (30s) may be too short for slow connections.
    • Fix: Adjust timeout in config or implement retry logic:
      timeout: 60  # Increase to 60 seconds
      
  4. Memory Leaks

    • Issue: Fetching large numbers of emails without limits can exhaust memory.
    • Fix: Always use getMessages($limit) and paginate results.
  5. IMAP Server Quirks

    • Issue: Some servers (e.g., Microsoft Exchange) require specific authentication methods ("login" vs "plain").
    • Fix: Test with debug: true in config and check server documentation.

Debugging Tips

  • Enable Debug Mode:

    debug: true
    

    Logs IMAP commands/responses to storage/logs/imap.log.

  • Check Connection Status:

    if (!$mailbox->isConnected()) {
        $mailbox->connect();
    }
    
  • Handle Exceptions: Catch Bartv2\ImapBundle\Exception\ImapException for connection/parsing errors.

Extension Points

  1. Custom Message Parsing Extend the Message class to add domain-specific logic:

    namespace App\Services;
    
    use Bartv2\ImapBundle\Model\Message as BaseMessage;
    
    class CustomMessage extends BaseMessage
    {
        public function isPromotional(): bool
        {
            return str_contains($this->getHeader('Subject'), 'Promo');
        }
    }
    

    Register the binding in a service provider:

    $this->app->bind(
        \Bartv2\ImapBundle\Model\Message::class,
        App\Services\CustomMessage::class
    );
    
  2. Proxy Support Configure proxies for corporate environments:

    proxy:
        socket: "tcp://proxy.example.com:8080"
        username: "proxy_user"
        password: "proxy_pass"
    
  3. Laravel Notifications Trigger notifications from parsed emails:

    if ($email->isPromotional()) {
        Notification::send($user, new PromotionalEmail($email));
    }
    
  4. Testing Use Laravel’s Mockery to simulate IMAP responses in tests:

    $mailbox = $this->app->make('imap.mailbox.inbox');
    $mailbox->shouldReceive('getMessages')
            ->andReturn([new CustomMessage()]);
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui