Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 解析电子邮件字段_Python_Email_Parsing - Fatal编程技术网

Python 解析电子邮件字段

Python 解析电子邮件字段,python,email,parsing,Python,Email,Parsing,我想从到:电子邮件字段解析电子邮件地址 事实上,在mbox中循环发送电子邮件时: mbox = mailbox.mbox('test.mbox') for m in mbox: print m['To'] 我们可以得到如下结果: info@test.org, Blahblah <blah@test.com>, <another@blah.org>, "Hey" <last@one.com> 是否有内置的东西(在邮箱或其他模块中)用于此功能,或者什么都没

我想从
到:
电子邮件字段解析电子邮件地址

事实上,在mbox中循环发送电子邮件时:

mbox = mailbox.mbox('test.mbox')
for m in mbox:
  print m['To']
我们可以得到如下结果:

info@test.org, Blahblah <blah@test.com>, <another@blah.org>, "Hey" <last@one.com>
是否有内置的东西(在
邮箱
或其他模块中)用于此功能,或者什么都没有


我读了几遍,但没有找到相关的东西。

电子邮件。parser
提供了您要查找的模块
email.message
仍然是相关的,因为解析器将使用此结构返回消息,因此您将从中获取标题数据。但要实际读取中的文件,
email.parser
是一种方法。

正如@TheSpooniest所指出的,
email
有一个解析器:

import email

s = 'info@test.org, Blahblah <blah@test.com>, <another@blah.org>, "Hey" <last@one.com>'

for em in s.split(','):
    print email.utils.parseaddr(em) 

Python提供了email.Header.decode_Header()用于解码头。函数对每个原子进行解码并返回元组列表(文本、编码),您仍然需要对这些元组进行解码和连接才能获得全文

对于地址,Python提供了email.utils.getaddresses(),用于在元组列表(显示名称、地址)中拆分地址。显示名称也需要解码,地址必须与RFC2822语法匹配。函数getmailaddresses()完成所有工作

这里有一个教程可能会对您有所帮助,您可以使用它:

>>> getaddresses(['info@test.org, Blahblah <blah@test.com>, <another@blah.org>, "Hey" <last@one.com>'])
[('', 'info@test.org'), ('Blahblah', 'blah@test.com'), ('', 'another@blah.org'), ('Hey', 'last@one.com')]
获取地址(['info@test.org,Blahblah,“嘿”]) [('', 'info@test.org","布拉布拉",blah@test.com'), ('', 'another@blah.org","嘿",last@one.com')]
(请注意,函数需要一个列表,因此您必须将字符串括在
[…]
中)

电子邮件解析程序如何将
的内容解析为
标题?如果名称或电子邮件中有逗号:
“例如,John”
,则此操作无效。
('', 'info@test.org')
('Blahblah', 'blah@test.com')
('', 'another@blah.org')
('Hey', 'last@one.com')
>>> getaddresses(['info@test.org, Blahblah <blah@test.com>, <another@blah.org>, "Hey" <last@one.com>'])
[('', 'info@test.org'), ('Blahblah', 'blah@test.com'), ('', 'another@blah.org'), ('Hey', 'last@one.com')]