PHP code example of thingmabobby / imap-email-checker

1. Go to this page and download the library: Download thingmabobby/imap-email-checker 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/ */

    

thingmabobby / imap-email-checker example snippets



declare(strict_types=1);

// Use Composer's autoloader
// Make sure to run 'composer install' in your project directory
Checker;
use DateTime;

// --- Configuration ---
// IMPORTANT: Store credentials securely (e.g., .env file, environment variables), not directly in code!
$hostname = getenv('IMAP_HOSTNAME') ?: '{your_imap_server:993/imap/ssl}INBOX';
$username = getenv('IMAP_USERNAME') ?: '[email protected]';
$password = getenv('IMAP_PASSWORD') ?: 'your_password';
$archiveFolder = getenv('IMAP_ARCHIVE_FOLDER') ?: 'Archive';

try {
    // Debug mode enabled (for more verbose logging of non-critical issues)
    $debugMode = true; // Set to true to enable debug logging (defaults to false)
    
    echo "Connecting to " . htmlspecialchars($hostname) . "...<br>";    
    $emailChecker = IMAPEmailChecker::connect($hostname, $username, $password, $debugMode);

    // --- Helper Function for Display ---
    function displayEmailDetails(array $email): void
    {
        $uid = $email['uid'] ?? 'N/A';
        echo "<h4>--- Details for Email UID: {$uid} ---</h4>";
        echo "<ul>";
        echo "<li><b>Subject:</b> " . htmlspecialchars($email['subject'] ?? 'N/A') . "</li>";
        echo "<li><b>From:</b> " . htmlspecialchars($email['from'] ?? 'N/A') . "</li>";
        echo "<li><b>Date:</b> " . htmlspecialchars($email['date'] ?? 'N/A') . "</li>";
        if (!empty($email['to'])) echo "<li><b>To:</b> " . htmlspecialchars(implode(', ', $email['to'])) . "</li>";
        if (!empty($email['cc'])) echo "<li><b>Cc:</b> " . htmlspecialchars(implode(', ', $email['cc'])) . "</li>";

        $body = $email['message_body'] ?? '';
        echo "<li><b>Body Length:</b> " . strlen($body) . " characters</li>";
        $snippet = mb_substr(strip_tags($body), 0, 100);
        echo "<li><b>Body Snippet:</b> " . htmlspecialchars($snippet) . "...</li>";

        $attachments = $email['attachments'] ?? [];
        if (!empty($attachments)) {
            echo "<li><b>Attachments (" . count($attachments) . "):</b><ul>";
            foreach ($attachments as $attachment) {
                $filename = htmlspecialchars($attachment['filename'] ?? 'unknown');
                $filesize = isset($attachment['content']) ? round(strlen($attachment['content']) / 1024) : 'N/A';
                $filetype = htmlspecialchars($attachment['type'] ?? 'unknown');
                echo "<li>{$filename} ({$filesize} KB, Type: {$filetype})</li>";
            }
            echo "</ul></li>";
        } else {
            echo "<li><b>Attachments:</b> None</li>";
        }
        echo "</ul>";
    }

    // ========================================================
    // --- Example Operations ---
    // ========================================================

    // 1. Check Mailbox Status
    echo "<h3>1. Mailbox Status:</h3>";
    $mailboxStatus = $emailChecker->checkMailboxStatus(); // Throws on failure
    echo "<ul>";
    echo "<li>Total Messages: " . $mailboxStatus['total'] . "</li>";
    echo "<li>Unseen Count: " . count($mailboxStatus['unseen_uids']) . "</li>";
    echo "<li>Highest UID: " . $mailboxStatus['highest_uid'] . "</li>";
    echo "</ul>";
    echo "<hr>";

    // 2. Check Unread Emails & Display Details
    echo "<h3>2. Processing Unread Emails:</h3>";
    $unreadEmails = $emailChecker->checkUnreadEmails(); // Throws on search failure
    $uidsToMarkRead = [];

    if (empty($unreadEmails)) {
        echo "<p>No unread emails found.</p>";
    } else {
        echo "<p>Found " . count($unreadEmails) . " unread emails. Processing details...</p>";
        // Note: processMessage failures inside checkUnreadEmails are logged & skipped
        foreach ($unreadEmails as $uid => $email) {
            displayEmailDetails($email);
            $uidsToMarkRead[] = $uid;
        }
        echo "<p>Last UID updated by checkUnreadEmails (if any processed): " . $emailChecker->lastuid . "</p>";

        // 3. Mark Processed Emails as Read
        if (!empty($uidsToMarkRead)) {
            echo "<h4>Marking " . count($uidsToMarkRead) . " emails as Read:</h4>";
            $emailChecker->setMessageReadStatus($uidsToMarkRead, true); // Throws on failure
            echo "<p>Successfully marked emails as read.</p>";
        }
    }
    echo "<hr>";

    // 4. Check emails since the last known UID (Incremental Check)
    echo "<h3>4. Checking New Emails Since Last Run:</h3>";
    $lastKnownUID = 0; // <<< Replace with loading logic from persistent storage
    echo "<p>Checking for emails newer than UID: " . $lastKnownUID . "</p>";
    $emailsSinceLastUID = $emailChecker->checkSinceLastUID($lastKnownUID); // Throws on overview failure
    $uidsProcessedInThisRun = [];

    if (empty($emailsSinceLastUID)) {
        echo "<p>No new emails found since UID " . $lastKnownUID . ".</p>";
    } else {
        echo "<p>Found " . count($emailsSinceLastUID) . " new emails.</p>";
        // Note: processMessage failures inside checkSinceLastUID are logged & skipped
        foreach ($emailsSinceLastUID as $uid => $email) {
            displayEmailDetails($email);
            $uidsProcessedInThisRun[] = $uid;
        }
        $newLastUID = $emailChecker->lastuid;
        echo "<p>Last UID updated to: " . $newLastUID . "</p>";
        // IMPORTANT: Store $newLastUID persistently for the next run
        // save_last_uid_to_storage($newLastUID);
    }
    echo "<hr>";

    // 5. Custom Search & Fetch Specific Messages
    echo "<h3>5. Custom Search & Fetch Specific Details:</h3>";
    $currentMonth = date('M-Y');
    $searchCriteria = 'TEXT ".pdf" SINCE "1-' . $currentMonth . '"';
    echo "<h4>Searching for: \"{$searchCriteria}\" (UIDs)</h4>";
    $pdfEmailUids = $emailChecker->search($searchCriteria); // Throws on failure or bad criteria

    if (empty($pdfEmailUids)) {
        echo "<p>No emails found matching criteria.</p>";
    } else {
        echo "<p>Found " . count($pdfEmailUids) . " matching UIDs: " . implode(', ', $pdfEmailUids) . ". Fetching details...</p>";

        // 6. Fetch the details ONLY for the messages found by search
        // Note: fetchMessagesByIds logs & skips individual message processing failures
        $pdfEmails = $emailChecker->fetchMessagesByIds($pdfEmailUids);

        if (empty($pdfEmails)) {
            echo "<p style='color: orange;'>Could not fetch details for any of the found UIDs (check logs).</p>";
        } else {
            echo "<p>Successfully fetched details for " . count($pdfEmails) . " emails:</p>";
            foreach ($pdfEmails as $uid => $email) {
                displayEmailDetails($email);
            }
        }
    }
    echo "<hr>";

    // --- Destructive Operations (Use with extreme caution!) ---
    $uids_to_process = $pdfEmailUids ?? $uidsToMarkRead ?? [];

    // 7. Delete an email by UID (Example: Last UID found)
    if (!empty($uids_to_process)) {
        $uid_to_delete = end($uids_to_process); // Get the last element
        echo "<h3>7. Attempting to Delete Email (UID {$uid_to_delete}):</h3>";
        echo "<p><strong>Warning: This action is permanent!</strong></p>";
        // Uncomment the following line ONLY if you are sure!
        // $emailChecker->deleteEmail($uid_to_delete); // Throws on failure
        // echo "<p>Email UID {$uid_to_delete} deleted successfully.</p>";
        echo "<p>(Deletion code is commented out for safety)</p>";
    } else {
        echo "<h3>7. Deleting Email:</h3><p>No UIDs available to demonstrate deletion.</p>";
    }
    echo "<hr>";

    // 8. Archive an email by UID (Example: First UID found)
    if (!empty($uids_to_process)) {
        $uid_to_archive = reset($uids_to_process); // Get the first element
        echo "<h3>8. Attempting to Archive Email (UID {$uid_to_archive}) to '{$archiveFolder}':</h3>";
        echo "<p><strong>Warning: This moves the email and expunges! Ensure folder '{$archiveFolder}' exists.</strong></p>";
        // Uncomment the following line ONLY if you are sure!
        // $emailChecker->archiveEmail($uid_to_archive, $archiveFolder); // Throws on failure
        // echo "<p>Email UID {$uid_to_archive} archived successfully.</p>";
        echo "<p>(Archival code is commented out for safety)</p>";
    } else {
        echo "<h3>8. Archiving Email:</h3><p>No UIDs available to demonstrate archival.</p>";
    }
    echo "<hr>";

} catch (\InvalidArgumentException $e) {
    // Handle errors related to invalid arguments passed to methods
    echo "<p style='color: purple; font-weight: bold;'>Argument Error: " . htmlspecialchars($e->getMessage()) . "</p>";
    // Log detailed error: error_log($e->getMessage() . "\n" . $e->getTraceAsString());
    exit(1);
} catch (\RuntimeException $e) {
    // Handle errors related to IMAP operations or other runtime issues
    echo "<p style='color: red; font-weight: bold;'>Runtime Error: " . htmlspecialchars($e->getMessage()) . "</p>";
    // Log detailed error: error_log($e->getMessage() . "\n" . $e->getTraceAsString());
    exit(1);
} catch (\Throwable $e) {
    // Catch any other unexpected errors
    echo "<p style='color: darkred; font-weight: bold;'>Unexpected Error: " . htmlspecialchars($e->getMessage()) . "</p>";
    // Log detailed error: error_log($e->getMessage() . "\n" . $e->getTraceAsString());
    exit(1);
}