Извлечение тела сообщения электронной почты из файла mbox, его декодирование в обычный текст независимо от кодировки и кодировки передачи содержимого

Я пытаюсь использовать Python 3 для извлечения тела сообщения электронной почты из файла thunderbird mbox. Это учетная запись IMAP.

Я хотел бы, чтобы текстовая часть тела электронного письма была доступна для обработки как строка Unicode. Оно должно «выглядеть так», как письмо в Thunderbird, и не содержать экранированных символов, таких как \ r \ n = 20 и т. Д.

Я думаю, что это кодировки передачи контента, которые я не знаю, как декодировать или удалять . Я получаю электронные письма с различными типами контента и разными кодировками передачи контента. Это моя текущая попытка:

import mailbox
import quopri,base64

def myconvert(encoded,ContentTransferEncoding):
    if ContentTransferEncoding == 'quoted-printable':
        result = quopri.decodestring(encoded)
    elif ContentTransferEncoding == 'base64':
        result = base64.b64decode(encoded)

mboxfile = 'C:/Users/Username/Documents/Thunderbird/Data/profile/ImapMail/server.name/INBOX'

for msg in mailbox.mbox(mboxfile):
    if msg.is_multipart():    #Walk through the parts of the email to find the text body.
        for part in msg.walk():
            if part.is_multipart(): # If part is multipart, walk through the subparts.
                for subpart in part.walk():
                    if subpart.get_content_type() == 'text/plain':
                        body = subpart.get_payload() # Get the subpart payload (i.e the message body)
                    for k,v in subpart.items():
                            if k == 'Content-Transfer-Encoding':
                                cte = v             # Keep the Content Transfer Encoding
            elif subpart.get_content_type() == 'text/plain':
                body = part.get_payload()           # part isn't multipart Get the payload
                for k,v in part.items():
                    if k == 'Content-Transfer-Encoding':
                        cte = v                      # Keep the Content Transfer Encoding

print(body)
print('Body is of type:',type(body))
body = myconvert(body,cte)
print(body)

Но это не удается:

Body is of type: <class 'str'>
Traceback (most recent call last):
File "C:/Users/David/Documents/Python/test2.py", line 31, in <module>
  body = myconvert(body,cte)
File "C:/Users/David/Documents/Python/test2.py", line 6, in myconvert
  result = quopri.decodestring(encoded)
File "C:\Python32\lib\quopri.py", line 164, in decodestring
  return a2b_qp(s, header=header)
TypeError: 'str' does not support the buffer interface
13
задан DCB 23 August 2011 в 20:08
поделиться