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...
php /* connect to gmail */ $hostname = '{imap.gmail.com:993/imap/ssl}INBOX'; $username = '[email protected]'; $password = 'davidwalsh'; /* try to connect */ $inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' .
IMAP stands for Internet Mail Access Protocol, PHP-IMAP functions helps you to access an email account and fetch emails from them. Using these functions you can also work with NNTP, POP3 protocols and local mailbox access methods. With the help of this library you can create web applications that handle your emails.
php /* connect to gmail */ $hostname = '{imap.gmail.com:993/imap/ssl}INBOX'; $username = 'my gmail id'; $password = 'my gmail password'; /* try to connect */ $inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' .
IMAP allows you to access your email wherever you are, from any device. When you read an email message using IMAP, you aren't actually downloading or storing it on your computer; instead, you're reading it from the email service.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With