Retrieve the 3 most recent email using imap and php
Asked Answered
S

3

5

I'm trying to figure out how to get the latest 3 emails (SEEN and UNSEEN) using imap and php. It need to be ressource-efficient since the mailbox as 1 000 emails inside. Getting all header may need too much ressources I think.

I just need the sender, the subject and the date...

Any idea? Thanks for any syggestion/help/explaination/hint...

Soninlaw answered 21/8, 2011 at 18:3 Comment(0)
O
12

I did it like that:

$mbox = imap_open("{imap.myconnection.com:993/imap/ssl}INBOX", "username", "password");

// get information about the current mailbox (INBOX in this case)
$mboxCheck = imap_check($mbox);

// get the total amount of messages
$totalMessages = $mboxCheck->Nmsgs;

// select how many messages you want to see
$showMessages = 5;

// get those messages    
$result = array_reverse(imap_fetch_overview($mbox,($totalMessages-$showMessages+1).":".$totalMessages));

// iterate trough those messages
foreach ($result as $mail) {

    print_r($mail); 

    // if you want the mail body as well, do it like that. Note: the '1.1' is the section, if a email is a multi-part message in MIME format, you'll get plain text with 1.1
    $mailBody = imap_fetchbody($mbox, $mail->msgno, '1.1');

    // but if the email is not a multi-part message, you get the plain text in '1'
    if(trim($mailBody)=="") {
        $mailBody = imap_fetchbody($mbox, $mail->msgno, '1');
    }

    // just an example output to view it - this fit for me very nice
    echo nl2br(htmlentities(quoted_printable_decode($mailBody)));
}

imap_close($mbox);

PHP-Ref IMAP: http://php.net/manual/en/ref.imap.php

Regards Dominic

Oster answered 27/1, 2017 at 16:19 Comment(0)
P
3

What about

imap_search($res, 'RECENT');

?

http://php.net/manual/en/function.imap-search.php

Prettify answered 21/8, 2011 at 18:8 Comment(1)
Can I limit the number of results during the search instead of getting all recent msg and then take only 3 messages?Soninlaw
S
1
$msgnos = imap_search($mbox, "UNSEEN", SE_UID);
$i=0;
foreach($msgnos as $msgUID) {
    $msgNo = imap_msgno($mbox, $msgUID);
    $head = imap_headerinfo($mbox, $msgNo);
    $mail[$i][] = $msgUID;
    $mail[$i][] = $head->Recent;    
    $mail[$i][] = $head->Unseen;    
    $mail[$i][] = $head->from[0]->mailbox."@".$head->from[0]->host; 
    $mail[$i][] = utf8_decode(imap_utf8($head->subject));   
    $mail[$i][] = $head->udate;
}
return $mail;
imap_close($mbox);

Will do the job.

Soninlaw answered 21/8, 2011 at 20:2 Comment(1)
And imap_close() won't be called after that return.Nikaniki

© 2022 - 2024 — McMap. All rights reserved.