Skip to content

Instantly share code, notes, and snippets.

@gwater
Created January 11, 2021 15:43
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 gwater/ec17020dbe2b765954b2017e436b0dec to your computer and use it in GitHub Desktop.
Save gwater/ec17020dbe2b765954b2017e436b0dec to your computer and use it in GitHub Desktop.
python script to query total unread emails from multiple servers
#!/usr/bin/env python
"""
small script to check for unread count on imap inbox
"""
import imaplib
import getpass
from pykeepass import PyKeePass
def count_unread(IMAPSERVER, PORT, USER, PASSWORD):
mail = imaplib.IMAP4(
IMAPSERVER,
port = PORT,
)
mail.starttls()
mail.login(USER, PASSWORD)
mail.select("inbox", True) # connect to inbox.
return_code, mail_data = mail.search(None, 'UnSeen')
mail_ids = mail_data[0].decode("UTF-8")
if len(mail_ids) == 0:
return 0
count = len(mail_ids.split(" "))
return count
inboxes = [
# (server, port, login user, keepass entry title)
("mail.example.com", 143, "user@example.com", "user@example.com"),
# add more inboxes as needed
]
pw = getpass.getpass()
try:
db = PyKeePass("example.kdbx", password = pw)
except:
print("could not open password database")
for i in inboxes:
entry = db.find_entries_by_title(i[3] + "*", regex = True, first=True)
try:
password = entry.password
except:
print(entry)
print("password not found for " + i[2])
password = ""
print(str(count_unread(*i[0:-1], entry.password)) + " – " + i[2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment