Mostafa Ayaz
Mostafa Ayaz

Reputation: 478

Decoding message headers and bodies in python

I'm trying to program a simple mail client in Python which can both send and read messages from inbox in gmail. The sending part works well, but the reading part keeps giving me a bad result.

Here is the python code:

import imaplib
import base64
email_user = '<gmail_address>'
email_pass = '<password>'

M = imaplib.IMAP4_SSL('imap.gmail.com', 993)
M.login(email_user, email_pass)
M.select('inbox')

typ, message_numbers = M.search(None, 'ALL')  # change variable name, and use new name in for loop


typ, data = M.fetch(b'1', '(RFC822)')
data1 = base64.b64decode(data[0][1])
print('Message \n%s' %data1)
M.close()
M.logout()

and the result is:

Message 
b'\r\xe9b\xbd\xea\xdeu:1\xcaf\xa2\x97M;\x82f\xa2\x95\xca&E\xe7\x1e\x8a\xf7\x9do-\xb4\xd3f\xb5\xef\xdd\x1a\xd7Nt\xd3M4\xc2+aH\xc4\xcf\x89\xdc\xb5\xea\xfe\x9c\xb2\x9d\xb8\xd3\xae\xbd\xf2\x98\xdd2\x89\xf5\xd4W\x9b\xdbM}\xd3nv\xd7\x9d<\xd3C\xd2Mt^q\xe8\xafy\xd6\xf2\xdbM6i\xd7\xfc\xdbgp\x8a\xd8R13\xe2w\x8d\xa6\xaf^\xbb\xefo{\xf3\n\xdb\xeb}y\xe3\xdf<\xdb}\xf9\xdfM\x8c\xa2}u\x15\xe6\xf6\xd3_t\xdb\x9d\xb5\xe7O4\xd0\xf4\x93\x01\x10\x92y\xa9b\xd5\xaa\xecj\xc8Z\xdb\x9e\xad\xd7\x9e=\xf3\xcd\xb7\xdf\x97/\x9e\x89\xdev\n(\x82W\x9c\xa2k'

I appreciate any modified code and hint. Also I'm new to python so please keep your descriptions as simple as possible...

Upvotes: 1

Views: 86

Answers (1)

tripleee
tripleee

Reputation: 189497

The message you receive in data[0][1] is not base64.

You want to do something like

from email import message_from_bytes
...
msg = message_from_bytes(data[0][1])

and then manipulate msg.

Upvotes: 1

Related Questions