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

Mailbox Connection Bundle Laravel Package

digitalshift/mailbox-connection-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require digitalshift/mailbox-connection-bundle
    

    Ensure pecl/mailparse is installed (pecl install mailparse).

  2. Enable the Bundle Add to config/bundles.php:

    return [
        // ...
        Digitalshift\MailboxConnectionBundle\DigitalshiftMailboxConnectionBundle::class => ['all' => true],
    ];
    
  3. Configure Define credentials in config/packages/digitalshift_mailbox_connection.yaml:

    digitalshift_mailbox_connection:
        connections:
            default:
                protocol: imap
                host: 'imap.example.com'
                port: 993
                username: 'user@example.com'
                password: 'password'
                ssl: true
    
  4. First Use Case Fetch the inbox folder and list messages in a controller:

    use Digitalshift\MailboxConnectionBundle\Entity\Folder;
    use Digitalshift\MailboxConnectionBundle\Entity\MimeMessage;
    
    public function inboxAction(ImapConnector $connector): Response
    {
        $folder = $connector->getFolder('INBOX');
        $messages = $folder->getMessages();
    
        return $this->render('mailbox/inbox.html.twig', [
            'messages' => $messages,
        ]);
    }
    

Implementation Patterns

Core Workflows

  1. Folder Management

    • Fetch folders recursively:
      $rootFolder = $connector->getFolder('');
      $subfolders = $rootFolder->getSubFolders();
      
    • Navigate to a specific folder:
      $folder = $connector->getFolder('INBOX/Subfolder');
      
  2. Message Processing

    • Fetch messages with pagination:
      $messages = $folder->getMessages(0, 10); // offset, limit
      
    • Access message metadata:
      /** @var MimeMessage $message */
      $subject = $message->getSubject();
      $from = $message->getFrom();
      $date = $message->getDate();
      
    • Parse MIME parts (attachments, HTML/Plaintext):
      $parts = $message->getParts();
      foreach ($parts as $part) {
          if ($part->isAttachment()) {
              $attachment = $part->getContent();
          }
      }
      
  3. Searching Messages

    • Use IMAP search criteria:
      $searchCriteria = [
          'SINCE' => '01-Jan-2023',
          'FROM' => 'sender@example.com',
          'SUBJECT' => 'important',
      ];
      $messages = $folder->searchMessages($searchCriteria);
      
  4. Dependency Injection

    • Inject ImapConnector into services/controllers:
      public function __construct(private ImapConnector $connector) {}
      

Integration Tips

  • Event Listeners: Extend functionality by listening to mailbox events (e.g., digitalshift.mailbox.folder.loaded).
  • Caching: Cache folder structures or message lists if performance is critical:
    $cache = $this->get('cache.app');
    $cacheKey = 'mailbox_folders_' . md5($folderPath);
    $folders = $cache->get($cacheKey, function() use ($connector, $folderPath) {
        return $connector->getFolder($folderPath)->getSubFolders();
    });
    
  • Background Processing: Use Symfony’s Messenger component to process large mailboxes asynchronously.

Gotchas and Tips

Pitfalls

  1. PECL Dependency

    • Issue: pecl/mailparse may not be pre-installed on shared hosting.
    • Fix: Ensure it’s installed via pecl install mailparse or use a Docker container with the dependency pre-configured.
  2. SSL/TLS Configuration

    • Issue: Some IMAP servers require specific SSL/TLS settings (e.g., ssl_verify_peer).
    • Fix: Extend the ImapConnector to pass additional stream context options:
      $connector->setStreamContext([
          'ssl' => [
              'verify_peer' => false,
              'allow_self_signed' => true,
          ],
      ]);
      
  3. Memory Limits

    • Issue: Large mailboxes or messages may exceed PHP’s memory limit.
    • Fix: Process messages in batches or use setMemoryLimit() on the connector.
  4. Folder Path Case Sensitivity

    • Issue: IMAP folder paths are case-sensitive on some servers.
    • Fix: Normalize paths before fetching:
      $folderPath = strtoupper('INBOX/subfolder');
      
  5. Connection Timeouts

    • Issue: Slow connections may time out.
    • Fix: Configure timeouts in the YAML:
      digitalshift_mailbox_connection:
          connections:
              default:
                  timeout: 30
      

Debugging

  • Enable Verbose Logging Add to config/packages/monolog.yaml:

    handlers:
        mailbox:
            type: stream
            path: "%kernel.logs_dir%/mailbox.log"
            level: debug
    

    Then enable debug mode in the connector:

    $connector->setDebug(true);
    
  • Check IMAP Errors Wrap connector calls in try-catch:

    try {
        $folder = $connector->getFolder('INBOX');
    } catch (\Digitalshift\MailboxConnectionBundle\Exception\ImapException $e) {
        // Log or handle error (e.g., retry logic)
    }
    

Extension Points

  1. Custom MIME Parsing Extend MimeMessage or override the mailparse behavior by creating a custom MimeMessageFactory:

    class CustomMimeMessageFactory extends MimeMessageFactory
    {
        public function createFromRaw($rawMessage): MimeMessage
        {
            // Custom logic here
            return parent::createFromRaw($rawMessage);
        }
    }
    

    Register it as a service:

    services:
        Digitalshift\MailboxConnectionBundle\Factory\MimeMessageFactory:
            class: App\Factory\CustomMimeMessageFactory
    
  2. Protocol-Specific Logic Use the ConnectorInterface to create protocol-agnostic services:

    public function processMessages(ConnectorInterface $connector, string $folderPath): void
    {
        $folder = $connector->getFolder($folderPath);
        // Works for IMAP/POP3 (when implemented)
    }
    
  3. Custom Folder Entities Extend the Folder entity to add metadata:

    class CustomFolder extends Folder
    {
        private $customMetadata;
    
        public function setCustomMetadata($metadata): self
        {
            $this->customMetadata = $metadata;
            return $this;
        }
    }
    

    Override the factory to return your custom entity.

  4. Async Processing Use Symfony’s Messenger to process messages in the background:

    $messageHandler = new ProcessMailMessageHandler($connector);
    $this->messageBus->dispatch(new ProcessMailMessage($message));
    
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.
craftcms/url-validator
directorytree/privacy-filter-classifier
directorytree/privacy-filter
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
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony