编程语言
首页 > 编程语言> > 如何从python的RFC 2822邮件标头中提取多个电子邮件地址?

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

作者:互联网

Python的电子邮件模块非常适合解析标头.但是,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>
$

解决方法:

通过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)

请注意,我重写了您的“收件人”行.我认为您的示例格式无效.

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

标签:rfc822,python,email
来源: https://codeday.me/bug/20191012/1898795.html