Search code examples
pythonimap

Python IMAP4 Don't Mark messages as read


I have a Python script to move messages with a certain subject. The messages get marked as read and I don't want them to be marked as read. What part of the script marks them as read and how do I make it not mark as read?

Also, I'm not too sure what I am doing yet, so if there is any redundant code or errors please let me know.

import getpass
from Crypto.Hash import MD5
import sys
import imaplib
import email
import re

password = getpass.getpass()
match = "redacted"

username  = "redacted"
dest = "000"
pattern_uid = re.compile('\d+ \(UID (?P<uid>\d+)\)')

def md5(message):
    hash = MD5.new()
    hash.update(message)
    return hash.hexdigest()

md5 = md5(password)

if md5 == match:
    pass
else:
    print "Mismatch"
    sys.exit()

M = imaplib.IMAP4_SSL("mail.redacted.com", 993)
M.login(username, password)
M.select()
typ, data = M.search(None, 'ALL')
M.select('Inbox')

msgs = M.search(None, 'ALL')[1]
num_messages = len(msgs[0].split())
num_messages += 1


def parse_uid(data):
    match = pattern_uid.match(data)
    return match.group('uid')

for i in range(1, num_messages):
    try:
        typ, msg_data = M.fetch(str(i), '(RFC822)')
    except:
        pass
    for response_part in msg_data:
        if isinstance(response_part, tuple):
            UID = M.fetch(str(i),'UID')
            UID = UID[1]
            try:
                UID = parse_uid(UID[0])
            except:
                pass
            msg = email.message_from_string(response_part[1])
            for header in [ 'subject'  ]:
                if msg[header] == "Redacted":
                    result = M.uid('COPY', UID, dest)
                    if result[0] == 'OK':
                        mov, data = M.uid('STORE', UID, '+FLAGS', '(\Deleted)')
                        M.expunge()


M.close()
M.logout()

Solution

  • typ, msg_data = M.fetch(str(i), '(RFC822)')

    Fetching a message body marks it as read. You'll want to use BODY.PEEK[].

    Although, I don't know why you're fetching the whole message just to copy it. Why don't you just fetch the headers? Use BODY.PEEK[HEADERS].