Installation:
composer require caponica/imap-bundle:dev-master
Add the bundle to app/AppKernel.php:
new Caponica\ImapBundle\CaponicaImapBundle(),
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'
Define Service (app/config/services.yml):
services:
caponica_imap_box:
class: Caponica\ImapBundle\Service\CaponicaImap
calls:
- [setConfig, ['%your_imap_config%']]
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));
}
}
Fetching Emails:
$mailbox = $this->get('caponica_imap_box')->getImapMailbox();
$emails = $mailbox->getMails(); // Returns raw email data
Searching Emails:
$searchResults = $mailbox->searchMails('SINCE "01-Jan-2023"');
Downloading Attachments:
$email = $mailbox->getMail($emailId);
$attachments = $email->getAttachments();
foreach ($attachments as $attachment) {
$attachment->downloadTo('%kernel.project_dir%/uploads/');
}
Flagging/Marking Emails:
$mailbox->markMail($emailId, IMAP_SEEN); // Mark as read
$mailbox->markMail($emailId, IMAP_ANSWERED); // Mark as answered
Batch Processing:
$mailbox->processMails(function ($email) {
if (strpos($email->getSubject(), 'invoice') !== false) {
// Handle invoice email
}
});
CaponicaImap service into services/controllers:
services:
app.mail_processor:
class: AppBundle\Service\MailProcessor
arguments: ['@caponica_imap_box']
$mailbox->onNewMail(function ($email) {
$this->dispatchEmailEvent($email);
});
$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
}
Connection Issues:
imapPath includes SSL/TLS (e.g., {imap.gmail.com:993/imap/ssl}).imap_open() before relying on the bundle.try {
$mailbox = $imapService->getImapMailbox();
} catch (\Exception $e) {
error_log($e->getMessage());
// Check for "IMAP connection failed" or "Login failed"
}
Memory Limits:
getMails($limit) or pagination:
$mailbox->getMails(100); // Fetch 100 emails at a time
Email Parsing Quirks:
if (!$email->isValid()) {
$this->handleMalformedEmail($email);
}
Directory Permissions:
directory in parameters.yml is writable by the web server:
chmod -R 775 %kernel.project_dir%/var/imap_cache
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:
{host:port/namespace}mailbox.INBOX, Sent, or custom folders).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']
Override Email Parsing: Replace the default email parser:
$mailbox->setEmailParser(new \AppBundle\Parser\CustomEmailParser());
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']]
How can I help you explore Laravel packages today?