2017-05-04 75 views
0

我有一個Python腳本來移動具有特定主題的郵件。郵件被標記爲已讀,我不希望它們被標記爲已讀。腳本的哪部分將它們標記爲已讀,以及如何使其不會標記爲已讀?Python IMAP4不要將郵件標記爲已讀

此外,我不太清楚我在做什麼,所以如果有任何多餘的代碼或錯誤,請讓我知道。

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() 

回答

1

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

擷取消息體將其標記爲已讀。你會想要使用BODY.PEEK[]

雖然,我不知道爲什麼你只是爲了複製它而獲取整條信息。你爲什麼不去取標題?使用BODY.PEEK[HEADERS]

+0

我在哪裏獲取郵件正文?在msg_data中,(RFC822)')? –

+0

我應該改變(RFC822)')到BODY.PEEK [HEADERS]? –

+0

它似乎被標記爲 UID = parse_uid(UID [0]) –

相關問題