如何从python中的RFC 2822邮件头中提取多个电子邮件地址?

时间:2015-11-03 23:54:52

标签: python email rfc822

Python的email模块非常适合解析标头。但是,To:标头可以包含多个收件人,并且可能有多个To:标头。那么如何拆分每个电子邮件地址?我不能分开逗号,因为逗号可以引用。有没有办法做到这一点?

演示代码:

msg="""To: user1@company1.com, "User Two" <user2@company2.com", "Three, User <user3@company3.com>                               
From: anotheruser@user.com                                                                                                      
Subject: This is a subject                                                                                                      

This is the message.                                                                                                            
"""

import email

msg822 = email.message_from_string(msg)
for to in msg822.get_all("To"):
    print("To:",to)

当前输出:

$ python x.py
To: user1@company1.com, "User Two" <user2@company2.com", "Three, User <user3@company3.com>
$ 

1 个答案:

答案 0 :(得分:2)

将所有To行传递到email.utils.getaddresses()

msg="""To: user1@company1.com, John Doe <user2@example.com>, "Public, John Q." <user3@example.com>
From: anotheruser@user.com
Subject: This is a subject

This is the message.
"""

import email

msg822 = email.message_from_string(msg)
for to in email.utils.getaddresses(msg822.get_all("To", [])):
    print("To:",to)

请注意,我重写了您的To行。我相信你的例子不是有效的格式。

参考:https://docs.python.org/2/library/email.util.html#email.utils.getaddresses