Python Email Parsing Issue

旧街凉风 提交于 2019-12-03 17:50:25

问题


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.


回答1:


Because you are using Python3, instead of using:

email.message_from_string(raw_email)

use:

email.message_from_bytes(raw_email)


来源:https://stackoverflow.com/questions/19508393/python-email-parsing-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!