[英]Not able to get gmail body inner text using imap in Python 3.6 +
[英]IMAP get sender name and body text?
我正在使用此代碼:
import imaplib
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(myusername, mypassword)
mail.list()
# Out: list of "folders" aka labels in gmail.
mail.select("inbox") # connect to inbox.
result, data = mail.search(None, "ALL")
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
print raw_email
並且它有效,除了當我打印raw_email
它返回一堆額外信息,我如何解析額外信息並僅獲取發件人和正文文本?
Python 的電子郵件包可能是一個很好的起點。
import email
msg = email.message_from_string(raw_email)
print msg['From']
print msg.get_payload(decode=True)
這應該問你問,雖然當一封電子郵件有多個部分(附件、文本和 HTML 版本的正文等)時,事情會更復雜一些。
在這種情況下, msg.is_multipart()
將返回 True 並且msg.get_payload()
將返回一個列表而不是一個字符串。 email.message文檔中有更多信息。
或者,您無需解析原始 RFC822 格式的消息(如果電子郵件包含附件,消息可能非常大),您只需向 IMAP 服務器詢問您想要的信息即可。 將您的mail.fetch
行更改為:
mail.fetch(latest_email_id, "(BODY[HEADER.FIELDS (FROM)])")
只會從服務器請求(並返回)電子郵件的From行。 同樣,將第二個參數設置為"(UID BODY[TEXT])"
將返回電子郵件的正文。 RFC2060有一個在這里應該有效的參數列表。
IMAP 高級庫: https : //github.com/ikvk/imap_tools (我是作者)
from imap_tools import MailBox, A
with MailBox('imap.mail.com').login('test@mail.com', 'password', 'INBOX') as mailbox:
for msg in mailbox.fetch(A(all=True)):
sender = msg.from_
body = msg.text or msg.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.