Tôi đang cố gắng sử dụng Python 3 để trích xuất nội dung thư email từ tệp mbox thunderbird. Đây là một tài khoản IMAP.Trích xuất nội dung của email từ tệp mbox, giải mã nó thành văn bản thuần túy bất kể Mã hóa chuyển mã và mã hóa
Tôi muốn có phần văn bản trong phần nội dung của email sẵn có để xử lý dưới dạng chuỗi unicode. Nó phải giống như 'email' trong Thunderbird và không chứa các ký tự thoát như \ r \ n = 20, v.v.
Tôi nghĩ rằng đó là Mã hóa chuyển nội dung mà tôi không biết cách giải mã hoặc tẩy. Tôi nhận được email với nhiều loại Nội dung khác nhau và Mã hóa Chuyển nội dung khác nhau. Đây là nỗ lực hiện tại của tôi:
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)
Nhưng điều này không thành công với:
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
Đó là lạ. get_payload() sẽ trả về byte, nhưng str theo Python 3, trừ khi bạn chuyển vào 'decode = True', mà bạn không làm. –
Tôi vừa thử nó với decode = True, và nó trả về byte, và do đó không có lỗi. Dường như việc giải mã được thực hiện, và bây giờ tất cả những gì tôi cần làm là chuyển đổi byte thành chuỗi. Mặc dù tôi vẫn chưa thử nghiệm với các email có nhiều loại mã hóa nội dung. – dcb
Huh, mà có vẻ như một lỗi, nó phải là cách khác xung quanh, giải mã = True nên trả về str và giải mã = False byte. :-) –