0

I'm trying to print the email body of all the emails from an specific sender, when I run the code I when an output of lines of this 5H6ONzrsveoHzDAKli/ and more random letters and signs. Here is the whole code. Thankyou

import imaplib
import pprint

imap_host = 'imap.gmail.com'
imap_user = 'user@googlemail.com'
imap_pass = 'password'

# connect to host using SSL
imap = imaplib.IMAP4_SSL(imap_host)

## login to server
imap.login(imap_user, imap_pass)

imap.select('Inbox')

tmp, data = imap.search(None, '(FROM "specific@gmail.com")')
for num in data[0].split():
    tmp, data = imap.fetch(num, '(RFC822)')
    #print('Message: {0}\n'.format(num))
    pprint.pprint(data[0][1])

    break
imap.close()
MIGUEL GP
  • 63
  • 5

1 Answers1

1

Try to import email module, and then create a message object using msg = email.message_from_bytes(data[0][1]) instead of pprint.pprint(data[0][1]).

data[0][1] is I think the whole email, not the body only.

After that you can loop through the parts of the message, and find the text/plain part of it. That will be your body. You can do it like:

for part in msg.walk():
    if part.get_content_type() == 'text/plain':
        print(part.get_payload())
    break
  • It doesn't work, the output shows the error " initial_value must be str or None, not bytes ". – MIGUEL GP Feb 03 '20 at 22:05
  • 1
    @MIGUELGP You are right, I believe the right function would be `email.message_from_bytes(data[0][1])` instead. Anyway, the [documentation](https://docs.python.org/3/library/email.parser.html) is very extensive, I believe you will find most answers to your questions inside. – small_cat_destroyer Feb 04 '20 at 09:53