What are the best practices for extracting and parsing email headers in PHP?

When extracting and parsing email headers in PHP, it is important to use built-in functions like `imap_headerinfo()` or `imap_fetchheader()` to retrieve the headers from an email message. Once the headers are obtained, you can use functions like `imap_rfc822_parse_headers()` or `imap_rfc822_parse_adrlist()` to parse specific header fields such as From, To, Subject, etc. These functions will help you extract and parse email headers accurately and efficiently.

// Connect to the IMAP server and retrieve the email headers
$hostname = '{imap.example.com:993/ssl}INBOX';
$username = 'email@example.com';
$password = 'password';

$mailbox = imap_open($hostname, $username, $password);
$headers = imap_headerinfo($mailbox, 1);

// Parse the From, To, and Subject headers
$from = $headers->from[0]->mailbox . "@" . $headers->from[0]->host;
$to = $headers->to[0]->mailbox . "@" . $headers->to[0]->host;
$subject = $headers->subject;

echo "From: $from\n";
echo "To: $to\n";
echo "Subject: $subject\n";

// Close the IMAP connection
imap_close($mailbox);