S
S
Sasha Filinsky2021-07-30 16:33:35
Python
Sasha Filinsky, 2021-07-30 16:33:35

Why is there an error when reading a letter from mail via IMAP?

All letters are read, but some give an error

Traceback (most recent call last):
  File "C:\Users\admin\Desktop\mail.py", line 121, in <module>
    if LastSubject != ReadingMail():
  File "C:\Users\admin\Desktop\mail.py", line 50, in ReadingMail
    body = payload.get_payload(decode=True).decode('UTF-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd0 in position 0: invalid continuation byte


piece of code
email_message = email.message_from_string(raw_email_string, policy=policy.default)
    
  if email_message.is_multipart():
    for payload in email_message.get_payload():
      body = payload.get_payload(decode=True).decode('UTF-8')
      #print(body)
  else:    
    body = email_message.get_payload(decode=True).decode('UTF-8')
    #print(body)

How to fix this error so that all letters are read without errors?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
ky0, 2021-07-30
@UkaUkaa

You are trying to process emails assuming they are all in utf8. Of course, in the case of other encodings, an error may occur.
Bring text to Unicode in advance, for example. Or cut out all invalid characters for it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question