在python中提取电子邮件标题 [英] Extract just email headers in python

查看:2251
本文介绍了在python中提取电子邮件标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些问题试图提取python中的所有电子邮件标题。我知道如何获得我正在寻找的,但我想保存所有的标题,我不知道如何做到这一点。



我将其加载到电子邮件对象中

  import email 
f = open(kwargs ['opt_emailfile'])
msg = email.message_from_file(f)
f.close()

所以我可以得到

  msg ['To'] 
msg ['From']

但是我想要所有的标题



解决方案



这是我做了什么感谢答案



$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
parser = email.parser.HeaderParser()
headers = parser.parsestr(msg.as_string())

在headers.items()中的h:
打印h


解决方案

使用HeaderParser 或许:

  from email.parser进口H eaderParser 
parser = HeaderParser()
h = parser.parsestr(email)

打印h.keys()

我刚刚注意到你编辑了你的问题。您实际上可以从您没有使用HeaderParser获取相同的信息。例如 headers.items() 将返回带有标题和相应值的2元组列表。


I'm having some issues trying to extract all the email headers in python. I know how to get the ones I'm looking for but I want to save all the headers and I'm not sure how to do that.

I have it loaded into a email object

import email
f = open(kwargs['opt_emailfile'])
msg = email.message_from_file(f)
f.close()

So I can get

msg['To']
msg['From']

But I want all the headers

Solution

Here is what I did thanks to the answer

        f = open(kwargs['opt_emailfile'])
        msg = email.message_from_file(f)
        f.close()

        parser = email.parser.HeaderParser()
        headers = parser.parsestr(msg.as_string())

        for h in headers.items():
            print h

解决方案

Using HeaderParser perhaps:

from email.parser import HeaderParser
parser = HeaderParser()
h = parser.parsestr(email)

print h.keys()

I just noticed you edited your question. You can actually get the same information from what you had without using HeaderParser. e.g. headers.items() will return list of 2-tuples with headers and corresponding values.

这篇关于在python中提取电子邮件标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆