I am writing a short script to monitor my inbox and get notified at every new incoming email. So far, I am using an infinite while loop like this:
msg_id_check = None
while True:
result, data = mail.fetch(mail.select('INBOX')[1][0], "(RFC822)") # mail is an imaplib object
msg_str = email.message_from_bytes(data[0][1])
msg_id = get_email_id(msg_str.get('Received'))
if msg_id == msg_id_check: # Don't keep notifying me of the same email
continue
FROM = msg_str.get('From')
SUBJECT = msg_str.get('Subject')
BODY = get_body(msg_str).decode()
print(f"Subject: {SUBJECT}\nFrom: {FROM}\nBody: {BODY}")
msg_id_check = msg_id
I first thought that I couldm't do this, because I've heard my computer when it gets stuck in an infinite loop and it does not sound like it enjoys it, but when I tried this code I didn't hear any noises from my computer, so I am wondering, is this a cpu-friendly process or is there a better way of getting notified at every incoming email?
P.S. Right now I am just printing new emails out to the screen, but in my project I need to do things with these emails and I do not want to lose any of these emails.