Last active
January 30, 2025 11:19
-
-
Save adrianpietka/30c915fa32b4777ee408 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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>'; |
Author
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
@miljushm Thanks. This gist was created 7 years ago. Only for my tests and fun. I don't want to change anything.