Search code examples
phpimap

displaying a message with imap_search based on a subject


I am trying to search with "subject" and "UNSEEN" using imap_search. It displays the subject and the name but not the message.

Is it possible to display the message based on a specific subject ?

my code :

set_time_limit(4000);

$imapPath = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = '[email protected]';
$password = '*****';

$inbox = imap_open($imapPath,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());

$emails = imap_search($inbox,'UNSEEN SUBJECT "aaa"');

$output = '';

if($emails) {
$output = '';
rsort($emails);
foreach($emails as $email_number) {
    $overview = imap_fetch_overview($inbox,$email_number,0);
    $message = imap_fetchbody($inbox,$email_number,2);
    $output.= '<div class="toggler '.($overview[0]->seen ? 'read' : 'unread').'">';
    $output.= '<span class="subject">'.$overview[0]->subject.'</span> ';
    $output.= '<span class="from">'.$overview[0]->from.'</span>';
    $output.= '<span class="date">on '.$overview[0]->date.'</span>';
    $output.= '</div>';
    $output.= '<div class="body">'.$message.'</div>';
}

echo $output;
} 
imap_expunge($inbox);
imap_close($inbox);

Solution

  • An e-mail message can contain a lot of data in various forms, so a hardcoded 2 won't work. See HOW to get mail structure with part number using imap command for details, then note that you'll have to undo Content-Transfer-Encoding, etc.