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

secit-pl/imap-bundle

Laravel bundle for IMAP email handling with a simple, configurable client. Connect to mailboxes, search and fetch messages, read headers and bodies, manage folders, and integrate IMAP operations into your Laravel app with minimal setup.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require secit-pl/imap-bundle
    

    Add to config/bundles.php:

    Secit\ImapBundle\SecitImapBundle::class => ['all' => true],
    
  2. Configuration Define IMAP servers in config/packages/secit_imap.yaml:

    servers:
        gmail:
            host: 'imap.gmail.com'
            port: 993
            encryption: ssl
            username: '%env(IMAP_USERNAME)%'
            password: '%env(IMAP_PASSWORD)%'
    
  3. First Use Case Fetch unread emails from Gmail in a controller:

    use Secit\ImapBundle\Service\ImapService;
    
    class EmailController extends AbstractController {
        public function __construct(private ImapService $imap) {}
    
        public function listUnread() {
            $emails = $this->imap->getEmails('gmail', ['UNSEEN']);
            return $this->json($emails);
        }
    }
    

Implementation Patterns

Core Workflows

  1. Fetching Emails

    // Get all emails with specific flags
    $this->imap->getEmails('gmail', ['SEEN', 'FLAGGED']);
    
    // Get emails with search criteria
    $this->imap->search('gmail', 'SINCE 1-Jan-2023');
    
  2. Email Processing

    foreach ($emails as $email) {
        $email->getHeaders(); // Array of headers
        $email->getBody();    // Raw body content
        $email->getAttachments(); // Array of attachments
    }
    
  3. Attachment Handling

    foreach ($email->getAttachments() as $attachment) {
        $attachment->saveTo($path); // Save to filesystem
        $attachment->getContent();  // Get raw content
    }
    
  4. Email Actions

    $this->imap->markAsRead('gmail', $email->getId());
    $this->imap->deleteEmail('gmail', $email->getId());
    $this->imap->moveEmail('gmail', $email->getId(), 'INBOX/Archive');
    

Integration Tips

  • Dependency Injection: Inject ImapService into services/controllers where email logic is needed.
  • Event Dispatching: Extend the bundle by dispatching events after email operations:
    $this->imap->afterFetch(function ($emails) {
        foreach ($emails as $email) {
            $this->dispatch(new EmailFetchedEvent($email));
        }
    });
    
  • Caching: Cache frequent queries (e.g., unread count) using Symfony’s cache system:
    $cache = $this->cache->get('gmail_unread_count', function () {
        return $this->imap->getEmailCount('gmail', ['UNSEEN']);
    });
    

Gotchas and Tips

Common Pitfalls

  1. Connection Issues

    • Symptom: Connection could not be established.
    • Fix: Verify host, port, and encryption in config. For Gmail, ensure "Less secure apps" is enabled or use an App Password.
    • Debug: Enable debug mode in secit_imap.yaml:
      debug: true
      
  2. Character Encoding

    • Symptom: Garbled text in email bodies.
    • Fix: Explicitly set encoding when fetching:
      $this->imap->getEmails('gmail', [], ['encoding' => 'UTF-8']);
      
  3. Rate Limiting

    • Symptom: Intermittent failures or timeouts.
    • Fix: Implement retries with exponential backoff:
      use Symfony\Component\Retry\Retry;
      
      Retry::until(function () use ($imap) {
          return $imap->getEmails('gmail');
      })->attempts(3)->delay(1000)->execute();
      
  4. Memory Limits

    • Symptom: Allowed memory exhausted when fetching large mailboxes.
    • Fix: Use limit parameter or fetch in batches:
      $this->imap->getEmails('gmail', [], ['limit' => 100]);
      

Debugging Tips

  • Log IMAP Commands: Enable debug mode and inspect logs for raw IMAP traffic.
  • Test with a Local Server: Use a tool like MailHog for local testing.
  • Validate Email IDs: IMAP IDs are not always sequential. Use getEmail() to verify existence before operations.

Extension Points

  1. Custom Email Models Override the default Email class by binding your own:

    # config/packages/secit_imap.yaml
    email_model: App\Entity\CustomEmail
    
  2. Pre/Post Hooks Extend the ImapService to add custom logic:

    $this->imap->onFetch(function ($emails) {
        // Pre-process emails
    });
    
    $this->imap->onDelete(function ($emailId) {
        // Post-delete logic
    });
    
  3. Custom Search Criteria Extend the search functionality by adding your own criteria:

    $this->imap->extendSearchCriteria(function ($criteria) {
        $criteria['CUSTOM'] = 'your_custom_logic';
    });
    
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.
yandex/translate-api
voku/simple_html_dom
league/flysystem-vfs
bkwld/upchuck
filament/spatie-laravel-tags-plugin
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
22h/doctrine-garbage-collection-bundle
agtp/agtp-php