Skip to content

Instantly share code, notes, and snippets.

@seppenen
Created May 14, 2018 19:08
Show Gist options
  • Save seppenen/0075c991adebe70732f94fe97be47ac8 to your computer and use it in GitHub Desktop.
Save seppenen/0075c991adebe70732f94fe97be47ac8 to your computer and use it in GitHub Desktop.
<?php
/* connect to gmail */
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = '****@gmail.com';
$password = 'PASSword';
echo "<script>console.log( 'Debug Objects: " . $username . "' ); </script>";
/* try to connect */
$items = array(
'msg' => array(),
'unseen_items' => array()
);
$mailbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
if ($mailbox === false) {
echo 'Error : ' . imap_last_error();
} else {
// Gets status information about the given mailbox
$status = imap_status($mailbox, "{" . $host . "}INBOX", SA_ALL);
if ($status === false) {
echo 'Error : ' . imap_last_error();
} else {
$items['msg']['all'] = $status->messages;
$items['msg']['unseen'] = $status->unseen;
// No unseen messages
if ($status->unseen == 0) {
echo 'No unseen messages';
} else {
// Gets UIDs for unseen messages
$messages = imap_search($mailbox, 'UNSEEN');
if ($messages === false) {
echo 'Error : ' . imap_last_error();
} else {
// For each all unseen messages
foreach($messages as $uid ) {
// Get header of the message
$message = imap_headerinfo($mailbox, $uid);
if ($message) {
// From message
$from = $message->from[0];
$from_addres = $from->mailbox . "@" . $from->host;
// Subject
$subject = isset($message->subject)
? imap_utf8($message->subject) : 'No subject';
// Re-format date
$date = date("Y-m-d H:i", strtotime($message->date));
// Add to data array
$items['msg']['unseen_items'][] = array(
$uid, $from_addres, $date, $subject
);
}
}
}
}
}
// Close an IMAP stream
imap_close($mailbox);
}
print_r(imap_errors());
// Show messages from data array
echo '<pre>' . print_r($items, true) . '</pre>';
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment