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\Connection
class (required)$message_num
- the message number you want to read the header from (required)$from_length
- the length of characters for thefrom
property (optional)$subject_length
- the length of characters for thesubject
property (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! 👍