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

ehymel/imap-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require secit-pl/imap-bundle
    

    (Note: The README mentions secit-pl/imap-bundle, but the package name in the description is ehymel/imap-bundle. Verify the correct package name in your project.)

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

    return [
        // ...
        Secit\ImapBundle\SecitImapBundle::class => ['all' => true],
    ];
    
  3. Configure IMAP Connection: Define connection settings in config/packages/secit_imap.yaml:

    secit_imap:
        connections:
            default:
                host: 'imap.example.com'
                port: 993
                encryption: ssl
                username: 'your_username'
                password: 'your_password'
                validate_cert: true
    
  4. First Use Case: Fetch emails in a controller:

    use Secit\ImapBundle\Service\ImapService;
    
    class EmailController extends AbstractController
    {
        public function __construct(private ImapService $imapService) {}
    
        public function index()
        {
            $emails = $this->imapService->getEmails('default');
            return $this->render('emails/index.html.twig', ['emails' => $emails]);
        }
    }
    

Implementation Patterns

Core Workflows

  1. Connection Management:

    • Use named connections (e.g., default, work, personal) for multi-account setups.
    • Dynamically switch connections via dependency injection:
      $this->imapService->setConnection('work');
      
  2. Email Retrieval:

    • Fetch all emails:
      $emails = $this->imapService->getEmails('default');
      
    • Fetch unread emails only:
      $emails = $this->imapService->getEmails('default', ['unread' => true]);
      
    • Fetch emails with custom criteria (e.g., since date):
      $emails = $this->imapService->getEmails('default', ['since' => '2023-01-01']);
      
  3. Email Processing:

    • Iterate over emails and access metadata:
      foreach ($emails as $email) {
          $subject = $email->getSubject();
          $from = $email->getFrom();
          $body = $email->getBody();
      }
      
    • Attachment handling:
      foreach ($email->getAttachments() as $attachment) {
          $attachment->saveTo('/path/to/save');
      }
      
  4. Searching Emails:

    • Use IMAP search criteria (e.g., BODY "invoice", FROM "support@example.com"):
      $emails = $this->imapService->searchEmails('default', 'BODY "receipt"');
      
  5. Sending Emails (if supported):

    • Configure SMTP in secit_imap.yaml and use:
      $this->imapService->sendEmail([
          'to' => 'recipient@example.com',
          'subject' => 'Hello',
          'body' => 'Email body',
      ]);
      

Integration Tips

  1. Symfony Events:

    • Trigger events after email retrieval (e.g., post.imap.email.fetched):
      # config/services.yaml
      Secit\ImapBundle\EventListener\ImapListener:
          tags:
              - { name: kernel.event_listener, event: post.imap.email.fetched, method: onEmailFetched }
      
  2. Caching:

    • Cache email lists to reduce IMAP load:
      $emails = $this->cache->get('emails_list', function() {
          return $this->imapService->getEmails('default');
      });
      
  3. Background Processing:

    • Use Symfony Messenger to process emails asynchronously:
      $this->messageBus->dispatch(new ProcessEmailMessage($email));
      
  4. Testing:

    • Mock the ImapService in tests:
      $this->mockImapService->expects($this->once())
          ->method('getEmails')
          ->willReturn([$mockEmail]);
      

Gotchas and Tips

Common Pitfalls

  1. Connection Issues:

    • Problem: SSL/TLS validation fails. Fix: Set validate_cert: false (not recommended for production) or ensure your server has a valid certificate.
    • Problem: Authentication fails silently. Debug: Enable debug mode in secit_imap.yaml:
      debug: true
      
      Check logs for IMAP errors.
  2. Performance:

    • Problem: Slow email retrieval with large inboxes. Fix: Use limit parameter:
      $this->imapService->getEmails('default', ['limit' => 50]);
      
      Or fetch only headers first:
      $this->imapService->getEmailHeaders('default');
      
  3. Encoding Issues:

    • Problem: Garbled email content. Fix: Ensure charset is set in secit_imap.yaml:
      secit_imap:
          default_charset: 'UTF-8'
      
  4. Attachment Handling:

    • Problem: Attachments not saving correctly. Fix: Verify file permissions and use absolute paths:
      $attachment->saveTo(sys_get_temp_dir() . '/attachment.pdf');
      
  5. Deprecation:


Debugging Tips

  1. Enable Verbose Logging:

    secit_imap:
        debug: true
        log_level: debug
    
  2. Raw IMAP Commands:

    • Access the underlying php-imap object for advanced debugging:
      $imapStream = $this->imapService->getImapStream('default');
      $rawResponse = imap_mailboxmsginfo($imapStream);
      
  3. Common IMAP Errors:

    • [PHP_IMAP] IMAP Error: Check credentials, server status, and firewall rules.
    • Connection timed out: Increase timeout in config:
      secit_imap:
          connections:
              default:
                  timeout: 30
      

Extension Points

  1. Custom Email Classes:

    • Extend Secit\ImapBundle\Entity\Email to add custom methods:
      class CustomEmail extends Email
      {
          public function isUrgent(): bool
          {
              return str_contains($this->getSubject(), 'URGENT');
          }
      }
      
    • Override the service to use your class:
      # config/services.yaml
      Secit\ImapBundle\Service\ImapService:
          arguments:
              $emailClass: App\Entity\CustomEmail
      
  2. Custom Search Criteria:

    • Add methods to ImapService to wrap complex searches:
      public function getUnreadInvoices(string $connectionName): array
      {
          return $this->searchEmails($connectionName, 'UNSEEN BODY "invoice"');
      }
      
  3. Event Dispatching:

    • Extend the bundle’s event system to trigger actions (e.g., notifications):
      // src/EventListener/EmailListener.php
      public function onEmailFetched(EmailFetchedEvent $event)
      {
          if ($event->getEmail()->isUrgent()) {
              $this->notificationService->alert('Urgent email received!');
          }
      }
      
  4. Connection Pooling:

    • Reuse connections across requests to avoid reconnecting:
      $this->imapService->persistConnection('default');
      
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware