使用Python的Mailbox模块读取mbox文件中的邮件内容

21
我尝试使用Python邮箱库打印邮件内容(邮件正文)。
import mailbox

mbox = mailbox.mbox('Inbox')
i=1
for message in mbox:
    print i
    print "from   :",message['from']
    print "subject:",message['subject']
    print "message:",message['**messages**']
    print "**************************************" 
    i+=1

但是我认为message['messages']不是正确的内容以打印邮件。我不能从文档中理解它。


更清晰的写法是:for i, message in enumerate(mbox):,这样就可以删除 i=1i+=1 - Nir
2个回答

21
为了获取邮件内容,您需要使用get_payload()mailbox.Messageemail.message.Message 的子类。您还需要检查is_multipart(),因为它会影响get_payload()的返回值。例如:
if message.is_multipart():
    content = ''.join(part.get_payload(decode=True) for part in message.get_payload())
else:
    content = message.get_payload(decode=True)

@cpburnz 所以它类似于 http://pastebin.com/AcYvDQM9 但是它没有工作。 :( - Technopolice
@LukasGraf 它没有打印出消息正文。 - Technopolice
@Sidnext2none,你需要print content,因为你正在将消息内容存储在content中。 - Uyghur Lives Matter
@cpburnz 哎呀...我犯了这么愚蠢的错误。问题已解决。谢谢你。 - Technopolice
1
@AllWorkersAreEssential 当我尝试打印(content)时,我收到了“TypeError: sequence item 0: expected str instance, bytes found”错误。 - Salih
@Salih,你可以将其放置在content = ''.join(str(part.get_payload(decode=True)) for part in message.get_payload())中,并使其成为字符串。不确定这可能会导致什么解码问题,但它将消除该错误。 - Hercislife

19
def getbody(message): #getting plain text 'email body'
    body = None
    if message.is_multipart():
        for part in message.walk():
            if part.is_multipart():
                for subpart in part.walk():
                    if subpart.get_content_type() == 'text/plain':
                        body = subpart.get_payload(decode=True)
            elif part.get_content_type() == 'text/plain':
                body = part.get_payload(decode=True)
    elif message.get_content_type() == 'text/plain':
        body = message.get_payload(decode=True)
    return body

如果消息主体是纯文本,此函数可以提供消息主体。


如何添加对“multipart/alternative”的支持? - Mark Colan
你可以替换 content_type。 - jOSe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接