1

I am trying to read a mail , which has html content in it. I am using message_from_bytes to read the data from mail.

def ParseEmail(email_user,email_pass,host,port,pdf):
    message_list = []
    mail = imaplib.IMAP4_SSL(host, port)
    mail.login(email_user, email_pass)
    mail.select()
    typ, data = mail.search(None, 'unseen')
    mail_ids = data[0]
    id_list = mail_ids.split()
    for num in id_list:
        typ, data = mail.fetch(num, '(RFC822)')
        raw = email.message_from_bytes(data[0][1])
        raw_email = data[0][1]
        raw_email_string = raw_email.decode('utf-8')
        email_message = email.message_from_string(raw_email_string)
        soup = BeautifulSoup(get_body(raw))
        content = soup.get_text('\n').replace('\xa0:\n\xa0\n', ' ')
        message_list.append(content)

the code compiles and runs without any error. when checked with IPython console, the message_list array is also printed. but, when I call this through driver functions I am getting error:

Traceback (most recent call last):
  File "parseemail.py", line 395, in <module>
    main()
  File "/Users/test/dev/Email/parseemail.py", line 384, in main
    pe = ParseEmail(email_user, email_pass, host, port,pdf)
  File "/Users/test/dev/Email/parseemail.py", line 320, in ParseEmail
    raw = email.message_from_bytes(data[0][1])
AttributeError: 'module' object has no attribute 'message_from_bytes'

what could br the possible error? (All the packages are installed and tested).

  • 2
    Do you happen to have a file called `email.py` in the same directory? – tripleee Sep 14 '19 at 07:23
  • By the by, you want to pass in a `policy` keyword argument to get the Python 3.6+ semantics. – tripleee Sep 14 '19 at 07:26
  • @tripleee what is that? where should I add policy keyword? – Akash Kumar Sep 14 '19 at 07:33
  • The `email` module was quietly overhauled in Python 3.3 and the new version became official in 3.6. But for backwards compatibility you still get the old API until a future version (I think Python 3.9?) unless you ask for the new one. In many case, you do this by adding an explicit policy argument. It's in [the documentation](https://docs.python.org/3/library/email.parser.html#email.message_from_bytes) and his box is really too small to explain this in detail. For new code, you probably want the new API. – tripleee Sep 14 '19 at 07:41
  • @tripleee will I be able to use its function with message_from_string? – Akash Kumar Sep 14 '19 at 07:48
  • You should probably prefer `message_from_bytes` but yes, both methods have this feature. Reading the documentation might be quicker than asking here about things it readily reveals. – tripleee Sep 14 '19 at 08:03
  • You were not responding to requests for clarification so I have assumed my first comment was correct in the end. If that is not the case and you still need help, please [edit] your question to include diagnostics like `email.__file__`. – tripleee Sep 14 '19 at 12:36

0 Answers0