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

dadadev/imap-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Run composer require dadadev/imap-bundle in your Symfony project. If using Symfony Flex, the bundle auto-registers. For older versions (2.8–3.x), manually add new DaDaDev\ImapBundle\ImapBundle() to AppKernel.

  2. Basic Configuration Configure config/packages/imap.yaml (Symfony 4+) or app/config/config.yml (Symfony 2.8–3.x):

    imap:
        connections:
            default:
                mailbox: "{your.imap.server:993/imap/ssl/novalidate-cert}INBOX"
                username: "[email protected]"
                password: "yourpassword"
    
  3. First Use Case: Fetch Emails Inject the DaDaDev\ImapBundle\Service\ImapService into a controller/service:

    use DaDaDev\ImapBundle\Service\ImapService;
    
    public function __construct(private ImapService $imapService) {}
    
    public function fetchEmails(): array
    {
        return $this->imapService->getConnection('default')->getMessages();
    }
    

Implementation Patterns

Core Workflows

  1. Connection Management

    • Define multiple connections in imap.yaml (e.g., production, staging).
    • Dynamically switch connections via getConnection('connection_name').
  2. Fetching and Processing Emails

    • Basic Fetch: Use getMessages() to retrieve raw email data (array of php-imap message objects).
      $messages = $this->imapService->getConnection('default')->getMessages();
      
    • Filtering: Apply criteria like getMessages(['unseen' => true]) or getMessages(['since' => '15-Jul-2023']).
    • Attachment Handling: Configure attachments_dir in YAML to auto-save attachments to a directory. Access via:
      $message->getAttachments(); // Returns array of paths
      
  3. Email Parsing

    • Use php-imap's built-in methods (e.g., $message->getHeader(), $message->getBody()) or extend the bundle:
      $headers = $message->getHeader();
      $body = $message->getBody();
      
  4. Marking as Read/Deleted

    • Leverage php-imap methods via the bundle:
      $this->imapService->getConnection('default')->markAsRead($messageId);
      $this->imapService->getConnection('default')->deleteMessage($messageId);
      
  5. Event-Driven Processing

    • Hook into Symfony events (e.g., kernel.request) to periodically check for new emails:
      $this->imapService->getConnection('default')->checkForNewMessages();
      

Integration Tips

  • Symfony Messenger: Dispatch email processing as async messages:
    $this->messageBus->dispatch(new ProcessEmailMessage($message));
    
  • Doctrine ORM: Map email data to entities:
    $emailEntity = (new Email())
        ->setSubject($message->getHeader('subject'))
        ->setBody($message->getBody());
    $entityManager->persist($emailEntity);
    
  • API Endpoints: Expose email data via API Platform or custom controllers:
    #[Route('/emails', methods: ['GET'])]
    public function listEmails(): JsonResponse
    {
        return $this->json($this->imapService->getConnection('default')->getMessages());
    }
    

Gotchas and Tips

Pitfalls

  1. Connection Timeouts

    • IMAP connections may hang. Use setTimeout() in the connection config (if supported by the underlying php-imap):
      imap:
          connections:
              default:
                  mailbox: "..."
                  timeout: 30 # seconds
      
    • Workaround: Implement retry logic in your service layer.
  2. SSL/TLS Validation

    • The novalidate-cert flag disables SSL cert validation (insecure). For production:
      • Use a valid SSL certificate on your IMAP server.
      • Avoid novalidate-cert in config.
  3. Attachment Paths

    • If attachments_dir isn’t writable, attachments won’t save. Verify permissions:
      chmod -R 755 var/imap/attachments
      
    • Tip: Use %kernel.project_dir%/var/imap/attachments for portability.
  4. Character Encoding

    • Mismatched server_encoding (e.g., UTF-8) may corrupt email content. Test with:
      $this->imapService->getConnection('default')->setEncoding('UTF-8');
      
  5. Memory Limits

    • Fetching large emails or many messages can exhaust memory. Use getMessages(['limit' => 50]) to paginate.
  6. Thread Safety

    • The bundle isn’t thread-safe. Avoid concurrent access to the same connection.

Debugging

  • Enable IMAP Debugging Add to your connection config:

    imap:
        connections:
            default:
                debug: true
    

    Logs will appear in var/log/dev.log.

  • Check IMAP Server Logs Server-side logs (e.g., dovecot.log) may reveal connection issues.

  • Validate Credentials Test credentials manually with telnet or openssl:

    openssl s_client -connect imap.example.com:993 -crlf
    a login username password
    

Extension Points

  1. Custom Message Processing Extend the DaDaDev\ImapBundle\Message\Message class to add domain-specific methods:

    class CustomMessage extends Message
    {
        public function isSpam(): bool
        {
            return str_contains($this->getHeader('subject'), 'SPAM');
        }
    }
    

    Override the bundle’s service definition to use your class.

  2. Add Connection Options Extend the DaDaDev\ImapBundle\Service\ImapConnection class to support custom php-imap options:

    $connection->setOption(IN_IMAP_KEEPALIVE, 1);
    
  3. Event Listeners Dispatch events for critical actions (e.g., new email received):

    // In your service:
    $this->eventDispatcher->dispatch(new EmailReceivedEvent($message));
    

    Listen globally in Symfony:

    services:
        App\EventListener\EmailListener:
            tags:
                - { name: kernel.event_listener, event: email.received, method: onEmailReceived }
    
  4. Mocking for Tests Use php-imap's mocking capabilities or create a test double for ImapService:

    $mockConnection = $this->createMock(ImapConnection::class);
    $mockConnection->method('getMessages')->willReturn([$mockMessage]);
    $this->imapService->setConnection('default', $mockConnection);
    
  5. Rate Limiting Implement a decorator around ImapService to enforce rate limits:

    class RateLimitedImapService implements ImapServiceInterface
    {
        public function getMessages(array $criteria = []): array
        {
            if ($this->isRateLimited()) {
                throw new \RuntimeException('Rate limit exceeded');
            }
            return $this->decorated->getMessages($criteria);
        }
    }
    
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle