python imaplib - mark email as unread or unseen

前端 未结 3 1667
夕颜
夕颜 2020-12-11 04:53

Searching here and on the internet, there are a lot of examples to how to mark a message as SEEN, even though this is automatic with imap.

But how can I mark an emai

相关标签:
3条回答
  • 2020-12-11 05:24

    You can easily clear the \Seen flags with this command:

    tag UID STORE -FLAGS (\Seen)
    

    but your software will probably be more robost if you only set the \Seen flag in the first place after you have successfully processed a message. That way, if anything goes wrong while you are processing a message (even if the connection to the IMAP server is broken) the flag remains unset and you can retry that message the next time the script runs. You do this by avoiding the IMAP server's automatic setting of the \Seen flag by using BODY.PEEK instead of BODY.

    In Python, I think that STORE command should be issued like this but I haven't tried it.

    connection.uid('STORE', '-FLAGS', '(\Seen)')
    
    0 讨论(0)
  • 2020-12-11 05:27

    In Python, the imaplib module describes STORE as:

    (typ, [data]) = <instance>.store(message_set, command, flags)
    

    so, the following line will let you set the message to READ ('+FLAGS') or UNREAD ('-FLAGS') as required.

    connection.uid('STORE', MESSAGE_ID, '+FLAGS', '\SEEN')
    

    As you see, the secrets is on the FLAGS command ;)

    0 讨论(0)
  • 2020-12-11 05:43

    You may use imap_tools package: https://pypi.org/project/imap-tools/

    with MailBox('imap.mail.com').login('test@mail.com', 'pwd', initial_folder='INBOX') as mailbox:
    
        # FLAG unseen messages in current folder as Answered and Flagged, *in bulk.
        flags = (imap_tools.StandardMessageFlags.ANSWERED, imap_tools.StandardMessageFlags.FLAGGED)
        mailbox.flag(mailbox.fetch('(UNSEEN)'), flags, True)
    
        # SEEN: mark all messages sent at 05.03.2007 in current folder as unseen, *in bulk
        mailbox.seen(mailbox.fetch("SENTON 05-Mar-2007"), False)
    
    0 讨论(0)
提交回复
热议问题