1

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...

1
  • For what it's worth, base64.b64encode(bytestring) decodes to b'DeliveredToxymail007gmailcomReceivedby2002a1790a10500000withSMTPidy16v6csp2406698pjdMon11Feb20190252150800PSTXReceivedby2002adf822dwithSMTPid42mr16772978wrb631549882335302Mon11Feb20190252150800PSTARCSeali1arsasha256t1549882335cvnonedgooglecoms=' -- this sort of reveals how desperately the base64 decoder had to struggle to make sense of your message. Commented Feb 11, 2019 at 12:24

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.