Skip to content

Instantly share code, notes, and snippets.

@ipimpat
Last active August 29, 2015 14:01
Show Gist options
  • Save ipimpat/7da10c1f302b8a4fedd1 to your computer and use it in GitHub Desktop.
Save ipimpat/7da10c1f302b8a4fedd1 to your computer and use it in GitHub Desktop.
Returns array of bodies of UNSEEN email message
<?php
/**
* Returns array of bodies of UNSEEN email message
* @param mixed $mbox array of mailbox, username and password OR mailbox opened with imap_open();
* @param string $sender optional: get only messages from $sender email address
*/
function mbox_get_unseen_messages($mbox, $sender = NULL)
{
// Email bodies
$bodies = array();
// Connect if not already a connecting we got passed
if(is_array($mbox)
{
list($mailbox, $username, $password) = $mbox
$mbox = imap_open($mailbox,$username, $password);
}
// Loop every message which havn't been read yet
foreach(imap_search($mbox, 'UNSEEN') as $message_id)
{
// Fetch message header
$header = imap_header($mbox, $message_id);
// Check that the message is from the expected sender
// however it is very easy to spoof tho :-)
if(!is_null($sender) AND $header->fromaddress !== $sender))
{
continue;
}
// Fetch the message body
$bodies[] = imap_fetchbody($mbox, $message_id, 1);
}
// Close the connecting
imap_close($mbox);
return $bodies;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment