Get only NEW Emails imaplib and python

前端 未结 5 1661
伪装坚强ぢ
伪装坚强ぢ 2020-12-04 14:49

This is a smaller portion of a bigger project. I need to only get unread emails and a parse their headers. How can I modify the following script to only get unread emails?

5条回答
  •  误落风尘
    2020-12-04 15:09

    The above answer does not actually work anymore or maybe never did but i modified it so it returns only unseen messages, it used to give : error cannot parse fetch command or something like that here is a working code :

    mail = imaplib.IMAP4_SSL('imap.gmail.com')
    (retcode, capabilities) = mail.login('email','pass')
    mail.list()
    mail.select('inbox')
    
    n=0
    (retcode, messages) = mail.search(None, '(UNSEEN)')
    if retcode == 'OK':
    
       for num in messages[0].split() :
          print 'Processing '
          n=n+1
          typ, data = mail.fetch(num,'(RFC822)')
          for response_part in data:
             if isinstance(response_part, tuple):
                 original = email.message_from_string(response_part[1])
    
                 print original['From']
                 print original['Subject']
                 typ, data = mail.store(num,'+FLAGS','\\Seen')
    
    print n
    

    I think the error was coming from the messages[0].split(' ') but the above code should work fine.

    Also, note the +FLAGS instead of -FLAGS which flags the message as read.

    EDIT 2020: If you pass by in 2020 after python 2.7 death: replace email.message_from_string(data[0][1]) with email.message_from_bytes(data[0][1])

提交回复
热议问题