簡體   English   中英

如何使用IMAP獲取正文消息

[英]How to get body message using IMAP

如何使用imaplib獲取消息正文

下面的代碼在終端中顯示None

mail.login("email@hotmail.com", "pass")
mail.list()
# Out: list of "folders" aka labels in gmail.
mail.select("inbox") # connect to inbox.

result, data = mail.search(None, '(FROM "sender@hotmail.com")')

ids = data[0] # data is a list.
id_list = ids.split() # ids is a space separated string
latest_email_id = id_list[-1] # get the latest

result, data = mail.fetch(latest_email_id, "(RFC822)") # fetch the email body (RFC822) for the given ID

raw_email = data[0][1] # here's the body, which is raw text of the whole email
# including headers and alternate payloads
msg = email.message_from_bytes(raw_email)

print(msg['Body'])

如果使用py2,請使用message_from_string而不是message_from_bytesmessage_from_bytes用於py3

import email
raw_email = email.message_from_string(data[0][1])
if not raw_email.is_multipart():
    print unicode(raw_email.get_payload(decode=True), raw_email.get_content_charset(), 'ignore').encode('utf8', 'replace')

如果是多件電子郵件,則需要遍歷零件...

for part in raw_email.get_payload():

並查看內容類型

if part.get_content_type() == 'text/plain':
    print unicode(part.get_payload(decode=True), str(charset), "ignore").encode('utf8', 'replace')

等等..

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM