Search code examples
pythonemailimapclient

read body of email using imapclient in python


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

Solution

  • 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)