Question

so I'm trying to write a script in python that logs into my gmail account and then tells me, soon in a GUI, what the message is. I will do a bit more stuff to the code later on to make it a bit program a bit more useful but right now I'm stuck on just being able to parse the raw information that I am getting. Here is my code:

#Read Email Script
import imaplib
import email

mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('username@gmail.com', 'passwordgoeshere')
mail.list()
mail.select("INBOX") # connect to inbox.


result, data = mail.search(None, "ALL")

ids = data[0]
id_list = ids.split()
latest_email_id = id_list[-1]

result, data = mail.fetch(latest_email_id, '(RFC822)')

raw_email = data[0][1]

email_message = email.message_from_string(raw_email)

print (email_message['Subject'])

Now this is basically supposed to try and read out the subject of the latest email that was delivered to my inbox. However I get the following error message in the console:

>>> 
Traceback (most recent call last):
  File "C:/Users/Dhruvin Desai/Documents/Python/script.py", line 21, in <module>
    email_message = email.message_from_string(raw_email)
  File "C:\Python33\lib\email\__init__.py", line 40, in message_from_string
    return Parser(*args, **kws).parsestr(s)
  File "C:\Python33\lib\email\parser.py", line 69, in parsestr
    return self.parse(StringIO(text), headersonly=headersonly)
TypeError: initial_value must be str or None, not bytes
>>> 

I don't know why this is coming up but since its telling me that the value of email_message needs to be in string format, I tried this:

email_message = email.message_from_string(str(raw_email))

But the result after running the entire script with that change always, no matter what, resulted in the console saying None

I don't know what to do, please help.

Was it helpful?

Solution

Because you are using Python3, instead of using:

email.message_from_string(raw_email)

use:

email.message_from_bytes(raw_email)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top