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

caponica/imap-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require caponica/imap-bundle:dev-master
    

    Add the bundle to app/AppKernel.php:

    new Caponica\ImapBundle\CaponicaImapBundle(),
    
  2. Configure Parameters (app/config/parameters.yml):

    your_imap_config:
        imapPath: '{imap.gmail.com:993/imap/ssl}INBOX'
        username: 'your_email@example.com'
        password: 'your_password'
        directory: '%kernel.project_dir%/var/imap_cache'
    
  3. Define Service (app/config/services.yml):

    services:
        caponica_imap_box:
            class: Caponica\ImapBundle\Service\CaponicaImap
            calls:
                - [setConfig, ['%your_imap_config%']]
    
  4. First Use Case: Fetch and sort emails in a controller:

    use Symfony\Component\HttpFoundation\Response;
    
    class MailController extends Controller
    {
        public function indexAction()
        {
            $imapService = $this->get('caponica_imap_box');
            $mailbox = $imapService->getImapMailbox();
            $emails = $mailbox->sortMails(SORTDATE); // SORTDATE, SORTARRIVAL, etc.
            return new Response(print_r($emails, true));
        }
    }
    

Implementation Patterns

Common Workflows

  1. Fetching Emails:

    $mailbox = $this->get('caponica_imap_box')->getImapMailbox();
    $emails = $mailbox->getMails(); // Returns raw email data
    
  2. Searching Emails:

    $searchResults = $mailbox->searchMails('SINCE "01-Jan-2023"');
    
  3. Downloading Attachments:

    $email = $mailbox->getMail($emailId);
    $attachments = $email->getAttachments();
    foreach ($attachments as $attachment) {
        $attachment->downloadTo('%kernel.project_dir%/uploads/');
    }
    
  4. Flagging/Marking Emails:

    $mailbox->markMail($emailId, IMAP_SEEN); // Mark as read
    $mailbox->markMail($emailId, IMAP_ANSWERED); // Mark as answered
    
  5. Batch Processing:

    $mailbox->processMails(function ($email) {
        if (strpos($email->getSubject(), 'invoice') !== false) {
            // Handle invoice email
        }
    });
    

Integration Tips

  • Dependency Injection: Inject CaponicaImap service into services/controllers:
    services:
        app.mail_processor:
            class: AppBundle\Service\MailProcessor
            arguments: ['@caponica_imap_box']
    
  • Event Listeners: Trigger actions on email events (e.g., new emails):
    $mailbox->onNewMail(function ($email) {
        $this->dispatchEmailEvent($email);
    });
    
  • Caching: Use Symfony’s cache system to store fetched emails:
    $cache = $this->get('cache.app');
    $cachedEmails = $cache->get('emails_' . $mailboxId);
    if (!$cachedEmails) {
        $cachedEmails = $mailbox->getMails();
        $cache->set('emails_' . $mailboxId, $cachedEmails, 3600); // Cache for 1 hour
    }
    

Gotchas and Tips

Pitfalls

  1. Connection Issues:

    • Ensure imapPath includes SSL/TLS (e.g., {imap.gmail.com:993/imap/ssl}).
    • Test credentials manually with imap_open() before relying on the bundle.
    • Debug with:
      try {
          $mailbox = $imapService->getImapMailbox();
      } catch (\Exception $e) {
          error_log($e->getMessage());
          // Check for "IMAP connection failed" or "Login failed"
      }
      
  2. Memory Limits:

    • Fetching large mailboxes may hit memory limits. Use getMails($limit) or pagination:
      $mailbox->getMails(100); // Fetch 100 emails at a time
      
  3. Email Parsing Quirks:

    • Some emails may not parse correctly due to malformed headers. Validate with:
      if (!$email->isValid()) {
          $this->handleMalformedEmail($email);
      }
      
  4. Directory Permissions:

    • Ensure the directory in parameters.yml is writable by the web server:
      chmod -R 775 %kernel.project_dir%/var/imap_cache
      

Debugging Tips

  • Enable IMAP Debugging:

    your_imap_config:
        imapPath: '{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX' # Disable cert validation for testing
    

    Log IMAP responses:

    $mailbox->setDebug(true);
    
  • Common Errors:

    • "Invalid IMAP path": Verify the format {host:port/namespace}mailbox.
    • "Login failed": Check credentials and IMAP server settings (e.g., Gmail requires "App Password" for 2FA).
    • "Mailbox does not exist": Confirm the mailbox name (e.g., INBOX, Sent, or custom folders).

Extension Points

  1. Custom Mailbox Classes: Extend Caponica\ImapBundle\Service\Mailbox to add methods:

    class CustomMailbox extends \Caponica\ImapBundle\Service\Mailbox
    {
        public function getUnreadCount()
        {
            return $this->searchMails('UNSEEN')->count();
        }
    }
    

    Register in services.yml:

    services:
        app.custom_mailbox:
            class: AppBundle\Service\CustomMailbox
            factory: ['@caponica_imap_box', 'createCustomMailbox']
    
  2. Override Email Parsing: Replace the default email parser:

    $mailbox->setEmailParser(new \AppBundle\Parser\CustomEmailParser());
    
  3. Add Custom Headers: Extend the Email class to include additional metadata:

    class ExtendedEmail extends \Caponica\ImapBundle\Model\Email
    {
        public function getCustomHeader($name)
        {
            return $this->headers->get($name, null);
        }
    }
    

    Bind the extended class in the service:

    services:
        caponica_imap_box:
            calls:
                - [setEmailClass, ['AppBundle\Model\ExtendedEmail']]
    
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.
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon