Parse Gmail with Python and mark all older than date as “read”

后端 未结 4 780
被撕碎了的回忆
被撕碎了的回忆 2020-12-28 10:45

Long story short, I created a new gmail account, and linked several other accounts to it (each with 1000s of messages), which I am importing. All imported messages arrive as

4条回答
  •  没有蜡笔的小新
    2020-12-28 11:42

    Based on Philip T.'s answer above and RFC 3501 and RFC 2822, I built some lines of code to mark mails older than 10 days as read. A static list is used for the abbreviated month names. This is not particularly elegant, but Python's %b format string is locale dependent, which could give unpleasant surprises. All IMAP commands are UID based.

    import imaplib, datetime
    
    myAccount = imaplib.IMAP4()
    myAccount.login(, )
    myAccount.select()
    
    monthListRfc2822 = ['0', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                        'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    beforeDate = datetime.datetime.today() - datetime.timedelta(days = 10)
    beforeDateString = ("(BEFORE %s-%s-%s)"
                        % (beforeDate.strftime('%d'),
                           monthListRfc2822[beforeDate.month],
                           beforeDate.strftime('%Y')))
    typ, data = myAccount.uid('SEARCH', beforeDateString)
    for uid in data[0].split():
        myAccount.uid('STORE', uid, '+FLAGS', '(\Seen)')
    

    By the way: I do not know, why "-" had to be used as a date delimiter in the search string in my case (dovecot IMAP server). To me that seems to contradict RFC 2822. However, dates with simple whitespace as delimiter only returned IMAP errors.

提交回复
热议问题