我收到一封包含以下代码的电子邮件:
m = imaplib.IMAP4_SSL(MailReceiveSRV)
m.login(MailReceiveUSER, MailReceivePWD)
m.select("Inbox")
status, unreadcount = m.status('INBOX', "(UNSEEN)")
unreadcount = int(unreadcount[0].split()[2].strip(').,]'))
items = m.search(None, "UNSEEN")
items = str(items[1]).strip('[\']').split(' ')
for index, emailid in enumerate(items):
resp, data = m.fetch(emailid, "(RFC822)")
email_body = data[0][1]
mail = email.message_from_string(email_body)
for part in mail.walk():
body = part.get_payload()
仅供引用:这始终是示例代码的一部分。
但是 body 现在是一个很大的对象列表。如果 Content_Type 是纯文本,那就容易多了。
我现在如何才能访问该邮件的正文?
最佳答案
简短回答
您有一封由多部分组成的电子邮件。这就是为什么您得到的是列表而不是字符串:如果是多部分消息,则 get_payload
返回 Message
列表,如果是多部分消息,则返回 string
不是。
说明
来自the docs :
Return the current payload, which will be a list of
Message
objects whenis_multipart()
isTrue
, or a string whenis_multipart()
isFalse
.
因此 get_payload
返回一个列表。
获取主体的代码类似于:
if email_message.is_multipart():
for part in email_message.get_payload():
body = part.get_payload()
# more processing?
else:
body = email_message.get_payload()
再次,from the docs :
Note that
is_multipart()
returningTrue
does not necessarily mean that "msg.get_content_maintype() == 'multipart'" will return theTrue
. For example,is_multipart
will returnTrue
when theMessage
is of type message/rfc822.
关于Python - 获取多部分电子邮件的正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30517621/