Search code examples
pythonwhile-loopgmail

Variable isn't updating as it should it be


I am trying to create a program where I am using a module called PGM. That is basically a gmail module. When I get the list of email ids and then get the number of ids in order to get the number of emails I have in my inbox, it works fine, but here is the thing when I put inside an infinite loop to check for any new emails, when I send an email to my inbox it doesn't update the number. It keeps printing the same value.

Here is the code.

import PGM,time
from playsound import playsound

mail = PGM.MailReader('username', 'password')

def sound():
    playsound('youve-got-mail-sound.mp3')




def countList():
    List = mail.get_mail_ids()
    count = len(List)
    tracker = count
    return tracker

countList()

while True:
    countList()
    print(countList())
    time.sleep(1)



Solution

  • Pure estimation:

    It might be that imap connection should be reopened on every check.

    When you try it yourself, a new connection is opened on each time and you get the latest results.

    When on loop, the same connection is used and you get the same result, since imaplib does not fetch the results from the server again.

    You could try this:

    while 1:
        mail = PGM.MailReader('username', 'password')
        # rest of your code logic
    

    just to see if it works.