title: TypeError: a bytes-like object is required, not 'str' but type shows bytes
body: <p>The output of this code:</p>
  
  <pre><code>print(type(body))
  body = body.replace('\n', '&lt;br&gt;')
  </code></pre>
  
  <p>produces:</p>
  
  <pre><code>&lt;class 'bytes'&gt;
  TypeError: a bytes-like object is required, not 'str'
  </code></pre>
  
  <p>Why is this type error occuring when body is a bytes object?</p>
  
  <p>I have also tested the <code>replace()</code> arguments as <code>b'\n', b'&lt;br&gt;</code> <a href="https://stackoverflow.com/questions/57101356/typeerror-a-bytes-like-object-is-required-not-str-but-type-is-bytes">as suggested in this question</a>, but no luck.</p>
  
  <pre><code>TypeError: replace() argument 1 must be str, not bytes
  </code></pre>
  
  <p>Here is the full code snippet, for reference I'm trying to display email content in html on a web page:</p>
  
  <pre><code>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'&lt;br&gt;')
      return body
    except errors.HttpError as error:
      print ('An error occurred: %s' % error)
  </code></pre>