How can PHP be used to format email subjects that come from an IMAP server?

When fetching email subjects from an IMAP server using PHP, they may contain special characters or be encoded in a specific format. To properly format these subjects for display, you can use the imap_utf8() function to decode any encoded characters and ensure proper display in your application.

// Connect to the IMAP server
$mailbox = imap_open('{mail.example.com:993/imap/ssl}INBOX', 'username', 'password');

// Fetch email subjects
$emails = imap_search($mailbox, 'ALL');

foreach ($emails as $email) {
    $header = imap_headerinfo($mailbox, $email);
    $subject = imap_utf8($header->subject);
    
    echo "Subject: $subject\n";
}

// Close the connection
imap_close($mailbox);