2015-11-03 39 views
2

Python的email模塊非常適合解析標題。但是,To:標題可以有多個收件人,並且可能有多個To:標題。那麼我如何拆分每個電子郵件地址?因爲逗號可以被引用,所以我不能在逗號分割。有沒有辦法做到這一點?如何從Python的RFC 2822郵件頭中提取多個電子郵件地址?

演示代碼:

msg="""To: [email protected], "User Two" <[email protected]", "Three, User <[email protected]>        
From: [email protected]                          
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: [email protected], "User Two" <[email protected]", "Three, User <[email protected]> 
$ 
+0

你想要什麼輸出? –

+1

可能你應該使用'shlex'&Co .. MDAs通過(未加引號)的逗號拆分地址行 – user3159253

+1

相關:https://docs.python.org/2/library/email.util.html#email.utils。 getaddresses –

回答

1

通過所有To線通過email.utils.getaddresses()

msg="""To: [email protected], John Doe <[email protected]>, "Public, John Q." <[email protected]> 
From: [email protected] 
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

+1

完美。我閱讀了文檔,但我無法找到我正在尋找的內容。謝謝! – vy32

相關問題