i get an email with the following code:
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()
FYI: This is always a part of the examplecode.
But body is now a biiig list of objects. If the Content_Type would be Plaintext, it would be much easier.
How can i get access to the body of that mail now?
You have a multiparted email. That's why you're getting a list instead of a string: get_payload
returns a list of Message
if it's a multipart message, and string
if it's not.
From the docs:
Return the current payload, which will be a list of
Message
objects whenis_multipart()
isTrue
, or a string whenis_multipart()
isFalse
.
Hence get_payload
returning a list.
Your code for getting the body would be something like:
if email_message.is_multipart():
for part in email_message.get_payload():
body = part.get_payload()
# more processing?
else:
body = email_message.get_payload()
Again, 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.