3

I am trying to view the actual body of an email. So far, I can view the subject, or any other headers, but I can't find a way to read just the body without extra stuff.

from imapclient import IMAPClient
import email

host = 'imap.gmail.com'
user = 'myEmailAddress'
password = 'myPassword'
ssl = True

server = IMAPClient(host, use_uid=True, ssl=ssl)
server.login(user, password)

inboxInfo = server.select_folder('INBOX')
messages = server.search(['NOT DELETED'])
response = server.fetch(messages, ['RFC822', 'BODY[TEXT]'])

for msgid, data in response.iteritems():
        parsedEmail = email.message_from_string(data['RFC822'])
        body = email.message_from_string(data['BODY[TEXT]'])
        parsedBody = parsedEmail.get_payload(0)
        print parsedBody

server.logout()

and that returns:

>From nobody Fri Jun  6 01:29:34 2014
>Content-Type: text/plain; charset=UTF-8
>
>Email body

I want to just return:

>Email body
0

1 Answer 1

-1

get_payload(i) returns a Message object.

You could use the Message.walk() method and test for text/plain

For example

for part in message.walk():
   if part.get_content_type() == "text/plain":
      do_stuff_with_text_parts(part)
2
  • 3
    yes it is wrong.get_payload returns str object. message_from_string function return Message Object. Mar 19, 2015 at 7:25
  • This is not correct answer. all get_payload does is return the dump the object that fetch gave you. this stuff [ print(message) for message in client.fetch( uids, [b'BODY[TEXT]']).values()] Jan 26, 2023 at 12:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.