koopmac
koopmac

Reputation: 966

TypeError: a bytes-like object is required, not 'str' but type shows bytes

The output of this code:

print(type(body))
body = body.replace('\n', '<br>')

produces:

<class 'bytes'>
TypeError: a bytes-like object is required, not 'str'

Why is this type error occuring when body is a bytes object?

I have also tested the replace() arguments as b'\n', b'<br> as suggested in this question, but no luck.

TypeError: replace() argument 1 must be str, not bytes

Here is the full code snippet, for reference I'm trying to display email content in html on a web page:

def GetMimeMessage(service, user_id, msg_id):

  try:
    message = service.users().messages().get(userId=user_id, id=msg_id, format='raw').execute()
    msg_bytes = base64.urlsafe_b64decode(message['raw'].encode('ASCII'))
    b = email.message_from_bytes(msg_bytes)
    body = ""

    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
    # not multipart - i.e. plain text, no attachments, keeping fingers crossed
    else:
      body = b.get_payload(decode=True)

    print(type(body))
    body = body.replace('\n', b'<br>')
    return body
  except errors.HttpError as error:
    print ('An error occurred: %s' % error)

Upvotes: 0

Views: 816

Answers (1)

Poojan
Poojan

Reputation: 3519

Change this

body = body.replace('\n', b'<br>')

to this

body = body.decode()
body = body.replace('\n', '<br>')
  • It looks like replace method is complaining because its byte like object. Please post content of body so it can be tested.

  • Here is example of sample case:

>>> s = b'asdf\nasdfa\n'
>>> s
b'asdf\nasdfa\n'
>>> s.replace('\n','<br>')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'
>>> s.decode().replace('\n','<br>')
'asdf<br>asdfa<br>'

Upvotes: 1

Related Questions