0

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.

elbashmubarmeg
  • 330
  • 1
  • 9
  • 1
    The email host might hate you as you are checking repeatedly as fast as the server can respond. I would recommend adding a time.sleep(300) in there or something so you check only every 5 minutes or some reasonable interval. – Chris Jun 20 '20 at 23:23

1 Answers1

0

When you send a request your program does't go further without awnser (can be timeout) so you have a "buffer" in your while loop but you don't need to know each second if you have a new mail you should put a time.sleep(60) at the end of the loop to send less useless requests

un random
  • 301
  • 1
  • 9