smartilabs/php-imap

PHP IMAP client

2.2.3 2020-11-02 12:43 UTC

README

Latest Version on Packagist Software License Build Status Total Downloads Hits

Description

PHP-IMAP is a wrapper for common IMAP communication without the need to have the php-imap module installed / enabled. The protocol is completely integrated and therefore supports IMAP IDLE operation and the "new" oAuth authentication process as well. You can enable the php-imap module in order to handle edge cases, improve message decoding quality and is required if you want to use legacy protocols such as pop3.

Wiki: webklex/php-imap/wiki

Laravel wrapper: webklex/laravel-imap

Table of Contents

Installation

1.) Install decoding modules:

sudo apt-get install php*-mbstring php*-mcrypt && sudo apache2ctl graceful

1.1.) (optional) Install php-imap module if you are having encoding problems:

sudo apt-get install php*-imap && sudo apache2ctl graceful

You might also want to check phpinfo() if the extensions are enabled.

2.) Now install the PHP-IMAP package by running the following command:

composer require webklex/php-imap

3.) Create your own custom config file like config/imap.php:

Configuration

Supported protocols:

  • imap — Use IMAP [default]
  • legacy-imap — Use the php imap module instead
  • pop3 — Use POP3
  • nntp — Use NNTP

The following encryption methods are supported:

  • false — Disable encryption
  • ssl — Use SSL
  • tls — Use TLS
  • starttls — Use STARTTLS (alias TLS) (legacy only)
  • notls — Use NoTLS (legacy only)

Detailed config/imap.php configuration:

  • default — used default account. It will be used as default for any missing account parameters. If however the default account is missing a parameter the package default will be used. Set to false to disable this functionality.
  • accounts — all available accounts
    • default — The account identifier (in this case default but could also be fooBar etc).
      • host — imap host
      • port — imap port
      • encryption — desired encryption method
      • validate_cert — decide weather you want to verify the certificate or not
      • username — imap account username
      • password — imap account password
      • authentication — imap authentication method. Use oauth to use oAuth for Google, etc.
  • date_format — The default date format is used to convert any given Carbon::class object into a valid date string. (d-M-Y, d-M-y, d M y)
  • options — additional fetch options
    • delimiter — you can use any supported char such as ".", "/", etc
    • fetchIMAP::FT_UID (message marked as read by fetching the message body) or IMAP::FT_PEEK (fetch the message without setting the "seen" flag)
    • fetch_body — If set to false all messages will be fetched without the body and any potential attachments
    • fetch_flags — If set to false all messages will be fetched without any flags
    • message_key — Message key identifier option
    • fetch_order — Message fetch order
    • common_folders — Default folder locations and paths assumed if none is provided
    • open — special configuration for imap_open()
      • DISABLE_AUTHENTICATOR — disable authentication properties.
    • decoder — Currently only the message and attachment decoder can be set
    • events — Default event handling config
    • masks — Default masking config
      • message — Default message mask
      • attachment — Default attachment mask

Usage

Basic usage example

This is a basic example, which will echo out all Mails within all imap folders and will move every message into INBOX.read. Please be aware that this should not be tested in real life and is only meant to gives an impression on how things work.

use Webklex\PHPIMAP\ClientManager;
use Webklex\PHPIMAP\Client;

$cm = new ClientManager('path/to/config/imap.php');

// or use an array of options instead
$cm = new ClientManager($options = []);

/** @var \Webklex\PHPIMAP\Client $client */
$client = $cm->account('account_identifier');

// or create a new instance manually        
$client = $cm->make([
    'host'          => 'somehost.com',
    'port'          => 993,
    'encryption'    => 'ssl',
    'validate_cert' => true,
    'username'      => 'username',
    'password'      => 'password',
    'protocol'      => 'imap'
]);

//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 ben moved';
        }else{
            echo 'Message could not be moved';
        }
    }
}

Folder / Mailbox

List all available folders:

/** @var \Webklex\PHPIMAP\Client $client */

/** @var \Webklex\PHPIMAP\Support\FolderCollection $folders */
$folders = $client->getFolders();

Get a specific folder:

/** @var \Webklex\PHPIMAP\Client $client */

/** @var \Webklex\PHPIMAP\Folder $folder */
$folder = $client->getFolder('INBOX.name');

oAuth

Please take a look at the wiki article for gmail / google mail setup.

Basic oAuth example:

use Webklex\PHPIMAP\Clientmanager;

$cm = new Clientmanager();

/** @var \Webklex\PHPIMAP\Client $client */
$client = $cm->make([
    'host' => 'imap.gmail.com',
    'port' => 993,
    'encryption' => 'ssl',
    'validate_cert' => true,
    'username' => 'example@gmail.com',
    'password' => 'ACCESS-TOKEN',
    'authentication' => "oauth",
    'protocol' => 'imap'
]);

//Connect to the IMAP Server
$client->connect();

Idle

Every time a new message is received, the server will notify the client and return the new message.

/** @var \Webklex\PHPIMAP\Folder $folder */
$folder->idle(function($message){
    echo $message->subject."\n";
});

Search for messages

Search for specific emails:

/** @var \Webklex\PHPIMAP\Folder $folder */

//Get all messages
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->all()->get();

//Get all messages from example@domain.com
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->from('example@domain.com')->get();

//Get all messages since march 15 2018
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->since('15.03.2018')->get();

//Get all messages within the last 5 days
$messages = $folder->query()->since(\Carbon\Carbon::now()->subDays(5))->get();

//Get all messages containing "hello world"
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->text('hello world')->get();

//Get all unseen messages containing "hello world"
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->unseen()->text('hello world')->get();

//Extended custom search query for all messages containing "hello world" 
//and have been received since march 15 2018
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->text('hello world')->since('15.03.2018')->get();
$messages = $folder->query()->Text('hello world')->Since('15.03.2018')->get();
$messages = $folder->query()->whereText('hello world')->whereSince('15.03.2018')->get();

// Build a custom search query
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()
->where([['TEXT', 'Hello world'], ['SINCE', \Carbon\Carbon::parse('15.03.2018')]])
->get();

//!EXPERIMENTAL!
//Get all messages NOT containing "hello world"
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->notText('hello world')->get();
$messages = $folder->query()->not_text('hello world')->get();
$messages = $folder->query()->not()->text('hello world')->get();

//Get all messages by custom search criteria
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->where(["CUSTOM_FOOBAR" => "fooBar"]])->get();

Available search aliases for a better code reading:

// Folder::search() is just an alias for Folder::query()
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->search()->text('hello world')->since('15.03.2018')->get();

// Folder::messages() is just an alias for Folder::query()
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->messages()->text('hello world')->since('15.03.2018')->get();

All available query / search methods can be found here: Query::class

Available search criteria:

  • ALL — return all messages matching the rest of the criteria
  • ANSWERED — match messages with the \ANSWERED flag set
  • BCC "string" — match messages with "string" in the Bcc: field
  • BEFORE "date" — match messages with Date: before "date"
  • BODY "string" — match messages with "string" in the body of the message
  • CC "string" — match messages with "string" in the Cc: field
  • DELETED — match deleted messages
  • FLAGGED — match messages with the \FLAGGED (sometimes referred to as Important or Urgent) flag set
  • FROM "string" — match messages with "string" in the From: field
  • KEYWORD "string" — match messages with "string" as a keyword
  • NEW — match new messages
  • NOT — not matching
  • OLD — match old messages
  • ON "date" — match messages with Date: matching "date"
  • RECENT — match messages with the \RECENT flag set
  • SEEN — match messages that have been read (the \SEEN flag is set)
  • SINCE "date" — match messages with Date: after "date"
  • SUBJECT "string" — match messages with "string" in the Subject:
  • TEXT "string" — match messages with text "string"
  • TO "string" — match messages with "string" in the To:
  • UNANSWERED — match messages that have not been answered
  • UNDELETED — match messages that are not deleted
  • UNFLAGGED — match messages that are not flagged
  • UNKEYWORD "string" — match messages that do not have the keyword "string"
  • UNSEEN — match messages which have not been read yet

Further information:

Result limiting

Limiting the request emails:

/** @var \Webklex\PHPIMAP\Folder $folder */

//Get all messages for page 2 since march 15 2018 where each page contains 10 messages
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->since('15.03.2018')->limit(10, 2)->get();

Counting messages

Count all available messages matching the current search criteria:

/** @var \Webklex\PHPIMAP\Folder $folder */

//Count all messages
/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$count = $folder->query()->all()->count();

//Count all messages since march 15 2018
$count = $folder->query()->since('15.03.2018')->count();

Pagination

Paginate a query:

/** @var \Webklex\PHPIMAP\Folder $folder */

/** @var \Illuminate\Pagination\LengthAwarePaginator $paginator */
$paginator = $folder->query()->since('15.03.2018')->paginate();

Paginate a message collection:

/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */

/** @var \Illuminate\Pagination\LengthAwarePaginator $paginator */
$paginator = $messages->paginate();

View example for a paginated list:

/** @var \Webklex\PHPIMAP\Folder $folder */

/** @var \Illuminate\Pagination\LengthAwarePaginator $paginator */
$paginator = $folder->search()
->since(\Carbon\Carbon::now()->subDays(14))->get()
->paginate($perPage = 5, $page = null, $pageName = 'imap_blade_example');
<table>
    <thead>
    <tr>
        <th>UID</th>
        <th>Subject</th>
        <th>From</th>
        <th>Attachments</th>
    </tr>
    </thead>
    <tbody>
        <?php if($paginator->count() > 0): ?>
            <?php foreach($paginator as $message): ?>
            <tr>
                <td><?php echo $message->getUid(); ?></td>
                <td><?php echo $message->getSubject(); ?></td>
                <td><?php echo $message->getFrom()[0]->mail; ?></td>
                <td><?php echo $message->getAttachments()->count() > 0 ? 'yes' : 'no'; ?></td>
            </tr>
            <?php endforeach; ?>
        <?php else: ?>
            <tr>
                <td colspan="4">No messages found</td>
            </tr>
        <?php endif; ?>
    </tbody>
</table>

<?php echo $paginator->links(); ?>

You can also paginate a Folder-, Attachment- or FlagCollection instance.

View examples

You can find a few blade examples under /examples.

Fetch a specific message

Get a specific message by uid (Please note that the uid is not unique and can change):

/** @var \Webklex\PHPIMAP\Folder $folder */

/** @var \Webklex\PHPIMAP\Message $message */
$message = $folder->query()->getMessage($msgn = 1);

Message flags

Flag or "unflag" a message:

/** @var \Webklex\PHPIMAP\Message $message */
$message->setFlag(['Seen', 'Spam']);
$message->unsetFlag('Spam');

Mark all messages as "read" while fetching:

/** @var \Webklex\PHPIMAP\Folder $oFolder */
/** @var \Webklex\PHPIMAP\Support\MessageCollection $aMessage */
$aMessage = $oFolder->query()->text('Hello world')->markAsRead()->get();

Don't mark all messages as "read" while fetching:

/** @var \Webklex\PHPIMAP\Folder $oFolder */
/** @var \Webklex\PHPIMAP\Support\MessageCollection $aMessage */
$aMessage = $oFolder->query()->text('Hello world')->leaveUnread()->get();

Attachments

Save message attachments:

/** @var \Webklex\PHPIMAP\Message $message */

/** @var \Webklex\PHPIMAP\Support\AttachmentCollection $attachments */
$attachments = $message->getAttachments();

$attachments->each(function ($attachment) {
    /** @var \Webklex\PHPIMAP\Attachment $attachment */
    $attachment->save("/some/path/");
});

Advanced fetching

Fetch messages without body fetching (decrease load):

/** @var \Webklex\PHPIMAP\Folder $folder */

/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->whereText('Hello world')->setFetchBody(false)->get();

/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->whereAll()->setFetchBody(false)->get();

Fetch messages without body, flag and attachment fetching (decrease load):

/** @var \Webklex\PHPIMAP\Folder $folder */

/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->whereText('Hello world')
->setFetchFlags(false)
->setFetchBody(false)
->get();

/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->whereAll()
->setFetchFlags(false)
->setFetchBody(false)
->get();

Change messages fetch order:

/** @var \Webklex\PHPIMAP\Folder $folder */

/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->whereText('Hello world')
->setFetchOrder('asc')
->get();

/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->whereAll()
->setFetchOrderAsc()
->get();

/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->whereAll()
->fetchOrderAsc()
->get();

/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->whereText('Hello world')
->setFetchOrder('desc')
->get();

/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->whereAll()
->setFetchOrderDesc()
->get();

/** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
$messages = $folder->query()->whereAll()
->fetchOrderDesc()
->get();

Events

The following events are available:

  • Webklex\PHPIMAP\Events\MessageNewEvent($message) — can get triggered by Folder::idle
  • Webklex\PHPIMAP\Events\MessageDeletedEvent($message) — triggered by Message::delete
  • Webklex\PHPIMAP\Events\MessageRestoredEvent($message) — triggered by Message::restore
  • Webklex\PHPIMAP\Events\MessageMovedEvent($old_message, $new_message) — triggered by Message::move
  • Webklex\PHPIMAP\Events\MessageCopiedEvent($old_message, $new_message) — triggered by Message::copy
  • Webklex\PHPIMAP\Events\FlagNewEvent($flag) — triggered by Message::setFlag
  • Webklex\PHPIMAP\Events\FlagDeletedEvent($flag) — triggered by Message::unsetFlag
  • Webklex\PHPIMAP\Events\FolderNewEvent($folder) — can get triggered by Client::createFolder
  • Webklex\PHPIMAP\Events\FolderDeletedEvent($folder) — triggered by Folder::delete
  • Webklex\PHPIMAP\Events\FolderMovedEvent($old_folder, $new_folder) — triggered by Folder::move

Create and register your own custom event:

class CustomMessageNewEvent extends Webklex\PHPIMAP\Events\MessageNewEvent {

    /**
     * Create a new event instance.
     * @var \Webklex\PHPIMAP\Message[] $messages
     * @return void
     */
    public function __construct($messages) {
        $this->message = $messages[0];
        echo "New message: ".$this->message->subject."\n";
    }
}

/** @var \Webklex\PHPIMAP\Client $client */
$client->setEvent("message", "new", CustomMessageNewEvent::class);

..or set it in your config file under events.message.new.

Masking

PHP-IMAP already comes with two default masks MessageMask::class and AttachmentMask::class.

The masked instance has to be called manually and is designed to add custom functionality.

You can call the default mask by calling the mask method without any arguments.

/** @var \Webklex\PHPIMAP\Message $message */
$mask = $message->mask();

There are several methods available to set the default mask:

/** @var \Webklex\PHPIMAP\Client $client */
/** @var \Webklex\PHPIMAP\Message $message */

$message_mask = \Webklex\PHPIMAP\Support\Masks\MessageMask::class;

$client->setDefaultMessageMask($message_mask);
$message->setMask($message_mask);
$mask = $message->mask($message_mask);

The last one wont set the mask but generate a masked instance using the provided mask.

You could also set the default masks inside your config/imap.php file under masks.

You can also apply a mask on attachments:

/** @var \Webklex\PHPIMAP\Client $client */
/** @var \Webklex\PHPIMAP\Attachment $attachment */
$attachment_mask = \Webklex\PHPIMAP\Support\Masks\AttachmentMask::class;

$client->setDefaultAttachmentMask($attachment_mask);
$attachment->setMask($attachment_mask);
$mask = $attachment->mask($attachment_mask);

If you want to implement your own mask just extend MessageMask::class, AttachmentMask::class or Mask::class and implement your desired logic:

/** @var \Webklex\PHPIMAP\Message $message */
class CustomMessageMask extends \Webklex\PHPIMAP\Support\Masks\MessageMask {

    /**
     * New custom method which can be called through a mask
     * @return string
     */
    public function token(){
        return implode('-', [$this->message_id, $this->uid, $this->message_no]);
    }
}

$mask = $message->mask(CustomMessageMask::class);

echo $mask->token().'@'.$mask->uid;

Additional examples can be found here:

Specials

Find the folder containing a message:

/** @var \Webklex\PHPIMAP\Message $message */
$folder = $message->getFolder();

Support

If you encounter any problems or if you find a bug, please don't hesitate to create a new issue. However please be aware that it might take some time to get an answer. Off topic, rude or abusive issues will be deleted without any notice.

If you need immediate or commercial support, feel free to send me a mail at github@webklex.com.

A little notice

If you write source code in your issue, please consider to format it correctly. This makes it so much nicer to read and people are more likely to comment and help :)

``` php

echo 'your php code...';

```

will turn into:

echo 'your php code...';

Features & pull requests

Everyone can contribute to this project. Every pull request will be considered but it can also happen to be declined. To prevent unnecessary work, please consider to create a feature issue first, if you're planning to do bigger changes. Of course you can also create a new feature issue if you're just wishing a feature ;)

Documentation

Client::class

Message::class

Folder::class

Query::class

Attachment::class

Mask::class

MessageMask::class

AttachmentMask::class

MessageCollection::class

Extends Illuminate\Support\Collection::class

FlagCollection::class

Extends Illuminate\Support\Collection::class

AttachmentCollection::class

Extends Illuminate\Support\Collection::class

FolderCollection::class

Extends Illuminate\Support\Collection::class

Known issues

Change log

Please see CHANGELOG for more information what has changed recently.

Security

If you discover any security related issues, please email github@webklex.com instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.