Laravel IMAP

repository·master·Indexed 20 days ago

https://github.com/webklex/laravel-imap

A Laravel library that integrates the native PHP-IMAP module and an extended custom IMAP protocol. It enables developers to read, parse, and respond to emails, as well as manage mailboxes. Features include a Client facade for account management, an imap:idle command for real-time message fetching, and a suite of events such as MessageNewEvent, MessageMovedEvent, and FolderNewEvent to trigger custom application logic.

Tokens
3.6K
Snippets
14
Records
17
Agent score
72%

What's inside webklex/laravel-imap

  1. Install Laravel IMAP

    master

    To install the Laravel IMAP library, ensure the mbstring PHP module is installed and enabled on your system. Then, use Composer to require the package.

    Prerequisite:

    sudo apt-get install php*-mbstring

    Installation:

    composer require webklex/laravel-imap
  2. Troubleshoot Kerberos credential errors

    master

    If you encounter the error Kerberos error: No credentials cache file found (try running kinit), follow these steps:

    1. Open your config/imap.php configuration file.
    2. Uncomment the DISABLE_AUTHENTICATOR option.
    3. Set the protocol to legacy-imap.
  3. Basic usage example for reading and moving emails

    master

    This example demonstrates how to connect to a default IMAP account, iterate through all available mailboxes, retrieve messages, and move them to a different folder (e.g., INBOX.read).

    Note: This is a demonstration script and should be used carefully in production environments.

    /** @var \Webklex\PHPIMAP\Client $client */
    $client = Webklex\IMAP\Facades\Client::account('default');
    
    //Connect to the IMAP Server
    $client->connect();
    
    //Get all Mailboxes
    /** @var \Webklex\PHPIMAP\Support\FolderCollection $folders */
    $folders = $client->getFolders();
    
    //Loop through every Mailbox
    /** @var \Webklex\PHPIMAP\Folder $folder */
    foreach($folders as $folder){
    
        //Get all Messages of the current Mailbox $folder
        /** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
        $messages = $folder->messages()->all()->get();
        
        /** @var \Webklex\PHPIMAP\Message $message */
        foreach($messages as $message){
            echo $message->getSubject().'<br />';
            echo 'Attachments: '.$message->getAttachments()->count().'<br />';
            echo $message->getHTMLBody();
            
            //Move the current Message to 'INBOX.read'
            if($message->move('INBOX.read') == true){
                echo 'Message has been moved';
            }else{
                echo 'Message could not be moved';
            }
        }
    }
  4. Configure IMAP accounts and defaults

    master

    The package uses a configuration file located at config/imap.php.

    Configuration Logic

    • Merging: Your local configuration is recursively merged with the package defaults. Local values will override package defaults.
    • Default Account: The default key in the config determines which account is used by default.
    • Disabling Defaults: You can disable the automatic application of default account parameters by setting imap.default to false in your configuration.
    • Account Inheritance: If a default account is specified, all other accounts in the accounts array will automatically inherit and merge parameters from that default account unless they explicitly override them.
  5. Access the IMAP Client via Laravel Service Container

    master

    The package registers two main singletons in the Laravel Service Container, allowing for easy dependency injection or resolution via the app() helper.

    ClientManager

    Resolves to Webklex\PHPIMAP\ClientManager. This is the primary entry point for managing multiple IMAP accounts.

    Client

    Resolves to Webklex\PHPIMAP\Client. This resolves to the specific account() instance associated with the default account defined in your imap.php configuration.

    // Resolving the default client directly
    $client = app(\Webklex\PHPIMAP\Client::class);
    
    // Resolving the manager to access specific accounts
    $manager = app(\Webklex\PHPIMAP\ClientManager::class);
    $specificClient = $manager->account('another_account_key');
  6. Access the IMAP client via the Client facade

    master

    The Webklex\IMAP\Facades\Client facade provides a static interface to the underlying ClientManager. You can use it to retrieve a specific configured account by name or create a new client instance with custom options.

    use Webklex\IMAP\Facades\Client;
    
    // Retrieve a configured account by its name
    $client = Client::account('default');
    
    // Create a new client instance with custom options
    $client = Client::make([
        'host' => 'imap.example.com',
        'port' => 993,
        'encryption' => 'ssl',
        'validate_cert' => true,
        'username' => 'user@example.com',
        'password' => 'password',
    ]);
  7. Implement custom logic for new messages in imap:idle

    master

    When using the ImapIdleCommand logic, you can define a callback to handle incoming Webklex\PHPIMAP\Message objects. In the provided implementation, the onNewMessage method is used as the callback for the $folder->idle() method.

    To process messages, you should override or implement the onNewMessage method to perform your desired actions, such as logging, database insertion, or notification dispatching.

    /**
     * Callback used for the idle command and triggered for every new received message
     * @param Message $message
     */
    public function onNewMessage($message) {
        // Your custom logic here
        $this->info("New message received: " . $message->subject);
    }
  8. Run the imap:idle command to fetch new messages

    master

    The imap:idle command allows you to listen for new messages in real-time using the IMAP IDLE extension. This command keeps a connection open and executes a callback whenever a new message is received in the specified folder.

    By default, the command uses the default account and the INBOX folder. To use this command effectively in a production environment, you typically want to extend or call this command logic to handle incoming messages (e.g., saving them to a database or triggering a job) rather than just printing the subject to the console.

    php artisan imap:idle
  9. Use Client::make() to create a new client instance

    master

    The make($options = []) method returns a \Webklex\PHPIMAP\Client instance initialized with the provided configuration options array.

    $client = Client::make([
        'host' => 'imap.example.com',
        'port' => 993,
        'encryption' => 'ssl',
        'username' => 'user@example.com',
        'password' => 'password',
    ]);
  10. Listen for the FlagNewEvent

    master

    The Webklex\IMAP\Events\FlagNewEvent is emitted whenever a new flag is added to an email message. You can listen for this event in your Laravel application to trigger custom logic (such as updating a database or notifying a user) when an email's status changes.

    The event object provides access to the specific message and the flag that was added.

    Properties:

    • $message: An instance of Webklex\PHPIMAP\Message representing the email.
    • $flag: A string representing the name of the newly added flag.
    use Webklex\IMAP\Events\FlagNewEvent;
    
    // Example of listening for the event in a ServiceProvider
    Event::listen(FlagNewEvent::class, function (FlagNewEvent $event) {
        $message = $event->message;
        $flag = $event->flag;
        
        // Perform custom logic here
        logger("New flag '{$flag}' added to message ID: {$message->getId()}");
    });