Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Email Parsing Issue

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('[email protected]', '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.

like image 641
bloodstorm17 Avatar asked Oct 22 '13 03:10

bloodstorm17


People also ask

What is parsing in email?

An email parser is a type of software application used for data extraction from incoming emails. A parsing API extracts text data from the email header and body. It can also parse information directly from email file attachments like PDF documents, CSV files, and MS Office files.


1 Answers

Because you are using Python3, instead of using:

email.message_from_string(raw_email)

use:

email.message_from_bytes(raw_email)
like image 91
Leonardo.Z Avatar answered Oct 16 '22 17:10

Leonardo.Z