4

I am trying to use imap_tools to fetch new emails. For some reason it only seems to fetch emails that were already in my inbox when I log in.

Can anyone see what I am doing wrong?

mailbox.login(email, password, initial_folder='INBOX')
print("Logging in")

for _ in range(50):
    try:
        msgs = mailbox.fetch(AND(new=True, subject='Order')) 
        print("Fetching emails")
        for msg in msgs:
            mail = msg.subject
            print(mail)
    except:
        pass

    sleep(1)

mailbox.logout()
print("Logging out")
Robsmith
  • 339
  • 1
  • 8

2 Answers2

0

1st mistake - you are not read "new" description: NEW - have the Recent flag set but not the Seen flag

2nd - instead fetch each second you can use IDLE

from imap_tools import MailBox, A

# waiting for updates 60 sec, print unseen immediately if any update
with MailBox('imap.my.moon').login('acc', 'pwd', 'INBOX') as mailbox:
    responses = mailbox.idle.wait(timeout=60)
    if responses:
        for msg in mailbox.fetch(A(seen=False)):
            print(msg.date, msg.subject)
    else:
        print('no updates in 60 sec')
Vladimir
  • 6,162
  • 2
  • 32
  • 36
  • Thanks @Vladimir. I don't understand the first point. I want to get new emails which have not been seen – James Mar 04 '22 at 14:01
  • @James, you want: (new emails AND NOT seen), you must determine for yourself what is "new" for you and how are you will manage it. – Vladimir Mar 05 '22 at 06:01
  • @Vladimir I tried this but new mails still don't show up, if I mark an old message as not seen from email client it will show in cli but if I send a new mail to the used mailbox the new mail doesn’t show up. – Isu Mar 29 '22 at 13:23
0

I faced the same problem and you just need to refresh the inbox before fetching function:

mailbox.login(email, password, initial_folder='INBOX')
print("Logging in")

for _ in range(50):
    try:
        mailbox.folder.set('INBOX')
        msgs = mailbox.fetch(AND(new=True, subject='Order')) 
        print("Fetching emails")
        for msg in msgs:
            mail = msg.subject
            print(mail)
    except:
        pass

    sleep(1)

mailbox.logout()
print("Logging out")