Skip to content

Instantly share code, notes, and snippets.

@adrianpietka
Last active January 30, 2025 11:19
Show Gist options
  • Select an option

  • Save adrianpietka/30c915fa32b4777ee408 to your computer and use it in GitHub Desktop.

Select an option

Save adrianpietka/30c915fa32b4777ee408 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>';
@miljushm
Copy link

miljushm commented Dec 8, 2022

You should use App Passwords in order to access the emails https://support.google.com/accounts/answer/185833

@adrianpietka
Copy link
Author

@miljushm Thanks. This gist was created 7 years ago. Only for my tests and fun. I don't want to change anything.

@miljushm
Copy link

miljushm commented Dec 8, 2022

You don't need to change anything because it works well, I just left the comment for the future in case somebody like @motsmanish has the issue with the login to Gmail (it now requires App Passwords) ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment