2011-11-04 146 views
2

大家好,我使用的腳本包括:1。電子郵件正文文本?

import oauth2 as oauth 
import oauth2.clients.imap as imaplib 
import email 
conn = imaplib.IMAP4_SSL('imap.googlemail.com') 
conn.debug = 4 

# This is the only thing in the API for impaplib.IMAP4_SSL that has 
# changed. You now authenticate with the URL, consumer, and token. 
conn.authenticate(url, consumer, token) 

# Once authenticated everything from the impalib.IMAP4_SSL class will 
# work as per usual without any modification to your code. 
conn.select('[Gmail]/All Mail') 

response, item_ids = conn.search(None, "SINCE", "01-Jan-2011") 
item_ids = item_ids[0].split() 

# Now iterate through this shit and retrieve all the email while parsing 
# and storing into your whatever db. 

for emailid in item_ids: 
    resp, data = conn.fetch(emailid, "(RFC822)") 
    email_body = data[0][1] 
    mail = email.message_from_string(email_body) 

我現在的問題是,我似乎無法能夠檢索mail實例的身體。我能夠通過打印或mail.as_string()來查看電子郵件的內容,但即使使用mail.keys()和mail.values(),我實際上也無法看到郵件的內容(主要消息)。

這封電子郵件lib API有什麼問題? (或者說我在做什麼錯誤)?

回答

4

email docs

您可以通過解析器字符串或一個文件對象,分析器將 回報給你的對象結構的根Message實例。

對於簡單的非MIME消息,此根對象的有效負載將爲 可能是包含消息文本的字符串。對於MIME 消息,根對象將從其is_multipart() 方法返回True,並且可以通過get_payload()和 walk()方法訪問子部分。

因此,使用get_payload()或者如果該消息是多然後調用walk()方法,然後在所希望的子部分使用get_payload()