I'm trying to get the last 10 emails of all emails unseen and seen - I also tried using an operator so "UNSEEN SEEN", but that doesn't seem to be working right for me as well.
This is the erro I get: Bad message number
Code:
private function RecentEmails(User $user)
{
$host = 'localhost';
$username = '';
$password = '';
// Connect to IMAP server
$inbox = imap_open('{'.$host.':993/ssl/novalidate-cert}INBOX', $username, $password);
// Check for errors
if (!$inbox) {
return []; // Handle error here
} else {
// Fetch recent emails
$unreadEmails = imap_search($inbox, 'UNSEEN', SE_UID);
$readEmails = imap_search($inbox, 'SEEN', SE_UID);
$recentEmails = [];
$emails = array_merge($unreadEmails ?: [], $readEmails ?: []);
// Initialize array to store recent emails
// Loop through fetched emails
if ($emails) {
// Limit the number of emails to fetch
$emails = array_slice($emails, 0, 10); // Fetching only the first 10 emails
foreach ($emails as $email) {
$headerInfo = imap_headerinfo($inbox, $email);
// Fetch email content
$emailStructure = imap_fetchstructure($inbox, $email);
$emailContent = imap_fetchbody($inbox, $email, 1); // Fetch plain text content
$emailContent = utf8_decode($emailContent);
// Check if the plain text content contains HTML tags
if (strpos($emailContent, '<html>') !== false) {
// If HTML tags are found, treat the content as HTML
$recentEmails[] = [
'sender' => $headerInfo->fromaddress,
'subject' => $headerInfo->subject,
'date' => date('Y-m-d H:i:s', strtotime($headerInfo->MailDate)),
'content' => $emailContent,
];
} else {
// If no HTML tags are found, treat the content as plain text
$recentEmails[] = [
'sender' => $headerInfo->fromaddress,
'subject' => $headerInfo->subject,
'date' => date('Y-m-d H:i:s', strtotime($headerInfo->MailDate)),
'content' => nl2br(htmlspecialchars($emailContent)), // Convert plain text to HTML
];
}
}
}
// Close the IMAP connection
imap_close($inbox);
return $recentEmails;
}
}
I've tried using an operator but that also didn't do anything. I've ran out of ideas.