Read emails using PHP via IMAP
2 min readJul 11, 2024
Everyone knows how to send emails using PHP using SMTP, but not all know how to read messages via IMAP in their PHP-based software.
Here you can find a simple snippet to read your email inbox:
$host = '{mail.domain.ltd:993/novalidate-cert/ssl}INBOX';
$user = 'user@domain.ltd';
$password = 'SecretPassword';
$imap = imap_open($host, $user, $password) or die('unable to connect: ' . imap_last_error());
// Get ALL emails or search for specific one
// e.g. imap_search($imap, 'SUBJECT "Invoice 123"');
$mails = imap_search($imap, 'ALL');
if ($mails) {
$mailOutput = '';
$mailOutput.= '<table><tr><th>Subject </th><th> From </th>
<th> Date Time </th> <th> Content </th></tr>';
rsort($mails);
foreach ($mails as $imap) {
$headers = imap_fetch_overview($imap, $email, 0);
$message = imap_fetchbody($imap, $email, '1');
$subMessage = substr($message, 0, 150);
$finalMessage = trim(quoted_printable_decode($subMessage));
$mailOutput.= '<div class="row">';
$mailOutput.= '<td><span class="columnClass">' .
$headers[0]->subject . '</span></td> ';
$mailOutput.= '<td><span class="columnClass">' .
$headers[0]->from . '</span></td>';
$mailOutput.= '<td><span class="columnClass">' .
$headers[0]->date . '</span></td>';
$mailOutput.= '</div>';
$mailOutput.= '<td><span class="column">' .
$finalMessage . '</span></td></tr></div>';
}
$mailOutput.= '</table>';
echo $mailOutput;
}
imap_close($imap);
You can also decide to auto-delete new messages after a fetch (e.g., into a cronjob) by adding this code to the previous snippet:
...
foreach ($mails as $email) {
...
imap_delete($imap, $email);
}
imap_expunge($imap);
imap_close($imap);
To read attachments, add this code to the previous snippet:
foreach ($mails as $email) {
$attachements = imap_fetchstructure($imap, $email);
foreach ($attachements->parts as $index_part => $part) {
if($part->ifdisposition) {
if ($part->disposition == "attachment") {
$filename = $part->dparameters[0]->value;
$attachment = imap_fetchbody($imap, $email, $index_part);
$file = fopen(__DIR__.'/attachments/'.uniqid().'/'.$filename), "w+");
fwrite($file, $attachment);
fclose($file);
}
}
...
}
This code could be used to build a Help Desk or to improve the User interaction with your application. I hope you enjoy it! ;)