2

I am trying to convert/decode byte to string and the code I've tried is shown as below:

body = ""
path = "C:\\Users\\...\\Demo"
listing = os.listdir(path)

for em in listing:
   mail = os.path.join(path, em)
   file = open(mail, 'rb')

   e_content = file.read()
   file.close()

   b = email.message_from_bytes(e_content)
   bbb = b['from']
   bbb = str(bbb)
   if '<' in bbb:
       bbb = bbb.split("<",1)[1]
       bbb = bbb[:-1]
       ccc = b['to']


   if b.is_multipart():
       for part in b.walk():
           ctype = part.get_content_type()
           cdispo = str(part.get('Content-Disposition'))

           # skip any text/plain (txt) attachments
           if ctype == 'text/plain' and 'attachment' not in cdispo:
               body = part.get_payload(decode=True)  # decode
               break


   else:
       body = b.get_payload(decode=True)


   mystring = str(body, 'utf-8','ignore')
   print(mystring)

Unfortunately, this code came out with this error:

mystring = str(body, 'utf-8','ignore')
TypeError: decoding str is not supported

What should I do to fix this? Any help is appreciated. :)

3
  • body is not bytes. Commented Dec 10, 2017 at 8:14
  • After the edit you made, the error changed, so should your post be updated, because your code and the error mentioned are not related now Commented Dec 10, 2017 at 8:22
  • @IgnacioVazquez-Abrams sorry for the confuse, I just update my code. The body is actually get from the email. Commented Dec 10, 2017 at 8:35

1 Answer 1

3

The following works for me with Python 2.7.12 and 3.5.2:

body = b'<html>\n<body>\n<p>Some text</p></body></html>'
mystring = body.decode('utf-8')
print(mystring)

Your updated code works for me with Python 3.5.2 but not with Python 2.7.12.

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.