我正在尝试对 mbox 格式的电子邮件进行一些处理。
搜索后,尝试了一些试验和错误https://docs.python.org/3/library/mailbox.html#mbox
我已经使用下面列出的测试代码完成了我想要的大部分工作(即使我必须编写代码来解码主题)。
我发现这有点偶然,特别是查找“主题”字段所需的关键似乎是反复试验,我似乎找不到任何方法来列出消息的候选人。(我了解这些字段可能因电子邮件而异。)
谁能帮我列出可能的值?
我还有一个问题;电子邮件可能包含许多“已接收:”字段,例如
Received: from awcp066.server-cpanel.com
Received: from mail116-213.us2.msgfocus.com ([185.187.116.213]:60917)
by awcp066.server-cpanel.com with esmtps (TLSv1.2:ECDHE-RSA-AES256-GCM-SHA384:256)
我有兴趣按时间顺序访问第一个 - 我很乐意搜索,但似乎找不到任何方法来访问文件中的第一个。
#! /usr/bin/env python3
#import locale
#2020-08-31
"""
Extract Subject from MBOX file
"""
import os, time
import mailbox
import base64, quopri
def isbqencoded(s):
"""
Test if Base64 or Quoted Printable strings
"""
return s.upper().startswith('=?UTF-8?')
def bqdecode(s):
"""
Convert UTF-8 Base64 or Quoted Printable string to str
"""
nd = s.find('?=', 10)
if s.upper().startswith('=?UTF-8?B?'): # Base64
bbb = base64.b64decode(s[10:nd])
elif s.upper().startswith('=?UTF-8?Q?'): # Quoted Printable
bbb = quopri.decodestring(s[10:nd])
return bbb.decode("utf-8")
def sdecode(s):
"""
Convert possibly multiline Base64 or Quoted Printable strings to str
"""
outstr = ""
if s is None:
return outstr
for ss in str(s).splitlines(): # split multiline strings
sss = ss.strip()
for sssp in sss.split(' '): # split multiple strings
if isbqencoded(sssp):
outstr += bqdecode(sssp)
else:
outstr += sssp
outstr+=' '
outstr = outstr.strip()
return outstr
INBOX = '~/temp/2020227_mbox'
print('Messages in ', INBOX)
mymail = mailbox.mbox(INBOX)
print('Values = ', mymail.values())
print('Keys = ', mymail.keys())
# print(mymail.items)
# for message in mailbox.mbox(INBOX):
for message in mymail:
# print(message)
subject = message['subject']
to = message['to']
id = message['id']
received = message['Received']
sender = message['from']
ddate = message['Delivery-date']
envelope = message['Envelope-to']
print(sdecode(subject))
print('To ', to)
print('Envelope ', envelope)
print('Received ', received)
print('Sender ', sender)
print('Delivery-date ', ddate)
# print('Received ', received[1])
基于这个答案,我简化了主题解码,并得到了类似的结果。
我仍在寻找访问标头其余部分的建议 - 特别是如何访问多个“已接收:”字段。
#! /usr/bin/env python3
#import locale
#2020-09-02
"""
Extract Subject from MBOX file
"""
import os, time
import mailbox
from email.parser import BytesParser
from email.policy import default
INBOX = '~/temp/2020227_mbox'
print('Messages in ', INBOX)
mymail = mailbox.mbox(INBOX, factory=BytesParser(policy=default).parse)
for _, message in enumerate(mymail):
print("date: :", message['date'])
print("to: :", message['to'])
print("from :", message['from'])
print("subject:", message['subject'])
print('Received: ', message['received'])
print("**************************************")