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
cattrain
  • 33
  • 1
  • 3

1 Answers1

-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)
data
  • 2,563
  • 1
  • 21
  • 25
  • 3
    yes it is wrong.`get_payload` returns str object. `message_from_string` function return Message Object. – Mohammad Razeghi Mar 19 '15 at 07: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()]` – Peter Moore Jan 26 '23 at 12:28