feat: unread mail counter

This commit is contained in:
Strix 2025-04-10 01:51:02 +02:00
parent d4496a2eda
commit cdbb47f6b9
5 changed files with 54 additions and 7 deletions

42
stats/mail.py Normal file
View file

@ -0,0 +1,42 @@
from prometheus_client import Gauge
import os
import imaplib
unread_mails = Gauge('unread_mails', 'Number of unread mails', ['mailbox'])
MAIL_SERVER = os.getenv("MAIL_SERVER")
MAIL_USER = os.getenv("MAIL_USER")
MAIL_PASS = os.getenv("MAIL_PASS")
MAIL_PORT = int(os.getenv("MAIL_PORT", 993))
print("[mail] Mail server:", MAIL_SERVER)
print("[mail] Mail user:", MAIL_USER)
print("[mail] Mail port:", MAIL_PORT)
def update():
try:
# handle secure differently, detect with port
if MAIL_PORT == 993:
mail = imaplib.IMAP4_SSL(MAIL_SERVER, MAIL_PORT)
else:
mail = imaplib.IMAP4(MAIL_SERVER, MAIL_PORT)
mail.login(MAIL_USER, MAIL_PASS)
mail.select("inbox")
result, data = mail.search(None, 'UNSEEN')
if result == 'OK':
unread_count = len(data[0].split())
unread_mails.labels(mailbox="inbox").set(unread_count)
else:
print(f"[mail] Error searching inbox: {data}")
unread_mails.labels(mailbox="inbox").set(0)
mail.close()
mail.logout()
except imaplib.IMAP4.error as e:
print(f"[mail] IMAP error: {e}")
unread_mails.labels(mailbox="inbox").set(0)
except ConnectionRefusedError:
print("[mail] Connection refused. Check your IMAP server settings.")
unread_mails.labels(mailbox="inbox").set(0)
except Exception as e:
print(f"[mail] Error checking unread mails: {e}")
unread_mails.labels(mailbox="inbox").set(0)