PHP code example of yaijs / php-ymap

1. Go to this page and download the library: Download yaijs/php-ymap library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

yaijs / php-ymap example snippets


use Yai\Ymap\ConnectionConfig;
use Yai\Ymap\ImapClient;

$config = new ConnectionConfig(
    '{imap.gmail.com:993/imap/ssl}INBOX',
    '[email protected]',
    'app-password'
);

$client = new ImapClient($config);
$client->connect();

foreach ($client->getUnreadUids() as $uid) {
    $message = $client->fetchMessage($uid);
    echo $message->getSubject();
    $client->markAsRead($uid);
}

use Yai\Ymap\ImapService;

$messages = ImapService::create()
    ->connect('{imap.gmail.com:993/imap/ssl}INBOX', '[email protected]', 'app-password')
    ->fields(['uid', 'subject', 'from', 'date', 'textBody'])
    ->{$msg['from'][0]['email']}\n";
}

use Yai\Ymap\ImapService;

$imap = new ImapService([
    'connection' => [
        'mailbox' => '{imap.gmail.com:993/imap/ssl}INBOX',
        'username' => '[email protected]',
        'password' => 'app-password',
        'options' => 0,
        'retries' => 3,
        'parameters' => [
            'DISABLE_AUTHENTICATOR' => 'GSSAPI',
        ],
    ],
    'fields' => ['uid', 'subject', 'from', 'date', 'textBody'],
    'filters' => [
        'limit' => 10,
        'since' => '2024-01-01',
        'unread' => true,
    ],
    'exclude' => [
        'from' => ['noreply@', 'newsletter@'],
        'subject_contains' => ['Unsubscribe', 'Digest'],
    ],
]);

$messages = $imap->getMessages();

use Yai\Ymap\ImapService;
use Yai\Ymap\Exceptions\ConnectionException;

try {
    ImapService::testConnection(
        '{imap.gmail.com:993/imap/ssl}INBOX',
        '[email protected]',
        'app-password'
    );
    echo 'Connection OK!';
} catch (ConnectionException $e) {
    echo 'Failed: ' . $e->getMessage();
}

$imap->excludeFrom(['noreply@', 'quora.com'])
     ->excludeSubjectContains(['Unsubscribe', 'Digest']);

$imap->markAsRead([1234, 1235]);
$imap->markAsUnread(1236);
$imap->markAsAnswered(1237);
$imap->markAsUnanswered(1238);

use Yai\Ymap\FetchOptions;

// Lightweight: Only metadata for inbox listings
$options = new FetchOptions(
    Critical for large attachments!
);

$messages = $service->getMessages($options);

// In your service configuration (e.g., services.xml, services.yaml)
<service id="YourApp\Service\EmailProcessorService">
    <argument type="service" id="Yai\Ymap\ImapService"/>
</service>

// In your scheduled task or background job
class EmailProcessorTask
{
    public function run(): void
    {
        $messages = $this->imapService
            ->fields(['uid', 'subject', 'from', 'preview'])
            ->limit(20)  // Process in batches
            ->unreadOnly()
            ->getMessages();

        foreach ($messages as $msg) {
            // Process message...
            $this->imapService->markAsRead($msg['uid']);
        }
    }
}

use Yai\Ymap\ImapClient;
use Yai\Ymap\ConnectionConfig;

$config = new ConnectionConfig(
    '{imap.gmail.com:993/imap/ssl}INBOX',
    '[email protected]',
    'app-password'
);

$client = new ImapClient($config);
$client->connect();

$message = $client->fetchMessage(12345);

foreach ($message->getAttachments() as $attachment) {
    // Stream directly to the filesystem (no giant strings in memory)
    $client->saveAttachmentTo(
        $message->getUid(),
        $attachment,
        '/tmp/' . $attachment->getFilename()
    );

    // Or access the content lazily
    if ($attachment->getMimeType() === 'application/pdf') {
        processPdf($attachment->getContent());
    }

    if ($attachment->isInline()) {
        $contentId = $attachment->getContentId(); // For referencing in HTML
    }
}

$messages = ImapService::create()
    ->connect('{imap.gmail.com:993/imap/ssl}INBOX', '[email protected]', 'app-password')
    ->fields(['uid', 'subject', 'attachments'])
    ->    }
}

use Yai\Ymap\ImapClient;
use Yai\Ymap\Connection\ImapConnectionInterface;

// Create a mock connection (PHPUnit example)
$mockConnection = $this->createMock(ImapConnectionInterface::class);
$mockConnection->method('search')
    ->willReturn([1, 2, 3]);

// Inject into ImapClient
$client = new ImapClient($config, connection: $mockConnection);

// Now $client->searchUIDs() returns mocked data

use Yai\Ymap\ImapService;
use Yai\Ymap\ImapClientInterface;

$service = ImapService::create()
    ->connect('{imap.host:993/imap/ssl}INBOX', '[email protected]', 'secret')
    ->useClient($container->get(ImapClientInterface::class));

use Yai\Ymap\Connection\ExtImapConnection;      // Optional: wraps ext-imap
use Yai\Ymap\Connection\SocketsImapConnection;  // Default: pure PHP socket connector

// Default in v1.0.3+: socket connector
$client = new ImapClient($config); // Uses SocketsImapConnection

// Optional override to native extension connector
$client = new ImapClient($config, connection: new ExtImapConnection());

use Yai\Ymap\Exceptions\ConnectionException;
use Yai\Ymap\Exceptions\MessageFetchException;

try {
    $messages = $imap->getMessages();
} catch (ConnectionException $e) {
    // Invalid credentials, TLS failure, server unreachable, etc.
} catch (MessageFetchException $e) {
    // Individual message could not be parsed/fetched
}

// Optional: capture per-message failures instead of silently skipping
$imap->onError(static function (int $uid, \Throwable $e): void {
    error_log(sprintf('Failed to fetch UID %d: %s', $uid, $e->getMessage()));
});

use Yai\Ymap\ImapService;

// ✓ Good: Use environment variables
$messages = ImapService::create()
    ->connect(
        getenv('IMAP_MAILBOX'),
        getenv('IMAP_USER'),
        getenv('IMAP_PASS')
    )
    ->getMessages();

// ✗ Bad: Hardcoded credentials
$messages = ImapService::create()
    ->connect('{imap.gmail.com:993/imap/ssl}INBOX', '[email protected]', 'password')
    ->getMessages();

// ✓ Good: SSL enabled
'{imap.gmail.com:993/imap/ssl}INBOX'

// ⚠️ Warning: Disables certificate validation (development only)
'{imap.example.com:993/imap/ssl/novalidate-cert}INBOX'

function sanitizeFilename(string $filename): string {
    // Remove path traversal attempts
    $filename = basename($filename);

    // Remove dangerous characters
    $filename = preg_replace('/[^a-zA-Z0-9._-]/', '_', $filename);

    // Prevent hidden files
    $filename = ltrim($filename, '.');

    return $filename ?: 'attachment.bin';
}

// Use it when saving attachments
foreach ($message->getAttachments() as $attachment) {
    $safeName = sanitizeFilename($attachment->getFilename());
    $client->saveAttachmentTo($message->getUid(), $attachment, "/secure/path/{$safeName}");
}
bash
composer 
bash
cd php-ymap/example
php -S localhost:8000
# open http://localhost:8000