Skip to content

Instantly share code, notes, and snippets.

@nickopris
Forked from adrianpietka/gmail-imap.php
Created October 19, 2023 09:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickopris/cb3794ca4df1f98dfdd252afc4feb5e0 to your computer and use it in GitHub Desktop.
Save nickopris/cb3794ca4df1f98dfdd252afc4feb5e0 to your computer and use it in GitHub Desktop.
<?php
// Turn off all error reporting
error_reporting(0);
// Configuration
$user = 'your_login';
$password = 'you_password';
$host = 'imap.gmail.com';
// Default data array
$items = array(
'msg' => array(),
'unseen_items' => array()
);
// Open an IMAP stream to a mailbox
$mailbox = imap_open("{" . $host . ":993/imap/ssl}INBOX", $user, $password, OP_READONLY);
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);
}
// 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