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

标签 python email rfc822

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

演示代码:

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() 传递所有 To 行:

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/3/library/email.utils.html#email.utils.getaddresses

关于python - 如何从 python 中的 RFC 2822 邮件 header 中提取多个电子邮件地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33511371/

相关文章:

python - TF 2.0 GPU cofingure,如何在pycharm中创建另一个虚拟环境后配置tensorflow-gpu 2.0和cuda、cudnn

python - C和python之间的RSA加密/解密

c# - Asp.net中的Email Delivery Message(如何查看邮件是否发送?)

python - 如何使用 Python 获取电子邮件文本内容?

python - 如何使用模拟来 stub 方法装饰器?

python - 基于 if 循环合并两个列表的内容

javascript - Mailto 链接导航到不同的网址

javascript - 使用 JavaScript 为 MS Outlook 生成长电子邮件正文

java - 如何在 Java 中将日期/时间从长(毫秒)转换为 RFC-822 格式

c# - 难倒在 C# DateTime ToString() 格式化问题