How to get mail date using php imap
To get the date of a mail using PHP and IMAP, you can use the imap_fetchheader
function to retrieve the email headers, and then parse the Date
header to get the date of the email.
Here is an example code snippet:
<?php
// Connect to the IMAP server
$imap = imap_open("{imap.example.com}", "username", "password") or die("Cannot connect to the IMAP server");
// Search for the email
$search = imap_search($imap, "ALL");
// Loop through the search results
foreach ($search as $msgno) {
// Fetch the email headers
$headers = imap_fetchheader($imap, $msgno);
// Parse the Date header
$date = imap_rfc822_parse_headers($headers);
$email_date = $date['date'];
// Print the email date
echo "Email date: $email_date\n";
}
// Close the IMAP connection
imap_close($imap);
?>
This code connects to an IMAP server, searches for all emails, loops through the search results, fetches the email headers, parses the Date
header using imap_rfc822_parse_headers
, and prints the email date.
Note that the imap_rfc822_parse_headers
function returns an array with several elements, including date
, which contains the date of the email in the format YYYY-MM-DD HH:MM:SS
.
Alternatively, you can use the imap_headerinfo
function to get the email headers and then extract the Date
header:
<?php
//...
foreach ($search as $msgno) {
// Fetch the email headers
$headers = imap_headerinfo($imap, $msgno);
// Get the Date header
$date = $headers->date;
// Print the email date
echo "Email date: $date\n";
}
//...
This code uses the imap_headerinfo
function to get the email headers, and then extracts the Date
header from the returned object.