I want to write a Python program that can connect to my Gmail account and tell me how many unread emails I have in my inbox. I tried looking for solutions but most examples I found are either too complicated or outdated.
Ideally, I would like to store my login credentials in a separate file instead of hardcoding them in the script for security reasons. What would be the best approach to accomplish this? Are there any specific libraries or APIs that work well for this kind of task?
I’m looking for a simple solution that doesn’t require too much setup. Any code examples would be really helpful.
Gmail API works, but using IMAP is simpler. I prefer Python’s built-in imaplib library, which eliminates the hassle of OAuth tokens or API quotas. To use it, just enable ‘Less secure app access’ in your Gmail settings or create an app password if 2FA is enabled. I store my login credentials in a config.ini file using configparser for better security. You can connect to imap.gmail.com, select the inbox, and then look for unseen emails by using mail.search(None, ‘UNSEEN’). Count the results, and that will give you the unread message count. This setup has been running smoothly for months without any authentication problems.
Gmail API with OAuth2 is hands down the most reliable method. IMAP can get disabled by Google whenever they feel like it, but the official API is way more stable and secure. You’ll need to set up credentials in Google Cloud Console and grab the credentials.json file. I use google-api-python-client with google-auth-oauthlib for auth. You have to run through OAuth once to create a token.pickle file, then it’s automatic after that. For unread counts, just query with q=‘is:unread in:inbox’ and check resultSizeEstimate. Been using this setup for over a year - zero auth issues or rate limiting headaches.
just tested both - Gmail API is way overkill for unread counts. went with imaplib and environment variables instead of config files. set GMAIL_USER and GMAIL_PASS in your system, then it’s literally 3 lines: connect to imap.gmail.com:993, login, and mail.status(‘INBOX’, ‘(UNSEEN)’) gets the count. much simpler than parsing message IDs.