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. :)
bodyis not bytes.bodyis actually get from the email.