The imap_headerinfo() function in PHP
The PHP imap_headerinfo() function is used to get the header of an email message using the IMAP protocol.
The syntax of the function is as follows:
imap_headerinfo(
IMAP\Connection $imap,
int $message_num,
int $from_length = 0,
int $subject_length = 0
): stdClass|false
The function parameters are as follows:
$imap- object instance of theIMAP\Connectionclass (required)$message_num- the message number you want to read the header from (required)$from_length- the length of characters for thefromproperty (optional)$subject_length- the length of characters for thesubjectproperty (optional)
The function will return an object containing the header information. When there’s an error, it returns false.
To create an $imap object, you need to call the imap_open() function.
The code template for using the imap_headerinfo() is as follows:
<?php
// ๐ establish IMAP connection
$url = "{localhost:993/imap/ssl}INBOX";
$id = "[email protected]";
$pwd = "your email password";
$imap = imap_open($url, $id, $pwd);
print("Connection established. \n");
// ๐ fetching header info with imap_headerinfo()
print("Headers of all messages: \n");
$res = imap_headerinfo($imap, 1);
print_r($res);
// ๐ close the IMAP connection
imap_close($imap);
When you successfully connected to the email server, you should see the header info printed on the screen.
An example of the header object is as follows:
stdClass Object (
[date] => Thu, 22 Aug 2022 20:10:52 +0000
[message_id] => [toaddress] => ****@mail.com
[to] => Array ( ... )
[fromaddress] => Sender [from] => Array ( ... )
[reply_toaddress] => Sender [reply_to] => Array ( ... )
[senderaddress] => Sender [sender] => Array ( ... )
[Recent] => [Unseen] => U [Flagged] =>
[Answered] => [Deleted] => [Draft] => [Msgno] => 2
[MailDate] => 22-Aug-2022 20:10:52 +0000
[Size] => 4858 [udate] => 1661173852
)
Now you’ve learned how the imap_headerinfo() function works in PHP. Nice work! ๐
More PHP tutorials
See allPHP
PHP form validation basic example
Dec 22, 2022
PHP
PHP validate email address (with code examples)
Dec 22, 2022
PHP
How to redirect using PHP with code examples
Dec 22, 2022
PHP
Handling form data using PHP (GET and POST)
Dec 21, 2022
PHP
How to fix Wordpress PHP error missing MySQL extension
Dec 21, 2022