<?php
// Connection details
$hostname = '{://gmail.com}INBOX';
$username = 'your-email@gmail.com';
$password = 'your-app-password';

// 1. Connect to the mailbox
$inbox = imap_open($hostname, $username, $password);

if ($inbox) {
    // 2. Get the total number of messages
    $total_emails = imap_num_msg($inbox);

    if ($total_emails > 0) {
        // 3. The last email has the highest index (total count)
        $last_email_index = $total_emails;
        
        // Fetch the email structure/overview
        $overview = imap_fetch_overview($inbox, $last_email_index, 0);
        $message = imap_fetchbody($inbox, $last_email_index, 1);

        echo "Subject: " . $overview[0]->subject . "\n";
        echo "From: " . $overview[0]->from . "\n";
        echo "Body: " . $message;
    } else {
        echo "Inbox is empty.";
    }

    // Always close the connection
    imap_close($inbox);
} else {
    echo 'Cannot connect to email server: ' . imap_last_error();
}
