title: Extracting the body of an email from mbox file, decoding it to plain text regardless of Charset and Content Transfer Encoding
body: <p>I am trying to use Python 3 to extract the body of email messages from a thunderbird mbox file. It is an IMAP account.</p>
  
  <p>I would like to have the text part of the body of the email available to process as a unicode string. It should 'look like' the email does in Thunderbird, and not contain escaped characters such as \r\n  =20 etc. </p>
  
  <p>I think that it is the Content Transfer Encodings that I don't know how to decode or remove.
  I receive emails with a variety of different Content Types, and different Content Transfer Encodings.
  This is my current attempt :</p>
  
  <pre><code>import mailbox
  import quopri,base64
  
  def myconvert(encoded,ContentTransferEncoding):
      if ContentTransferEncoding == 'quoted-printable':
          result = quopri.decodestring(encoded)
      elif ContentTransferEncoding == 'base64':
          result = base64.b64decode(encoded)
  
  mboxfile = 'C:/Users/Username/Documents/Thunderbird/Data/profile/ImapMail/server.name/INBOX'
  
  for msg in mailbox.mbox(mboxfile):
      if msg.is_multipart():    #Walk through the parts of the email to find the text body.
          for part in msg.walk():
              if part.is_multipart(): # If part is multipart, walk through the subparts.
                  for subpart in part.walk():
                      if subpart.get_content_type() == 'text/plain':
                          body = subpart.get_payload() # Get the subpart payload (i.e the message body)
                      for k,v in subpart.items():
                              if k == 'Content-Transfer-Encoding':
                                  cte = v             # Keep the Content Transfer Encoding
              elif subpart.get_content_type() == 'text/plain':
                  body = part.get_payload()           # part isn't multipart Get the payload
                  for k,v in part.items():
                      if k == 'Content-Transfer-Encoding':
                          cte = v                      # Keep the Content Transfer Encoding
  
  print(body)
  print('Body is of type:',type(body))
  body = myconvert(body,cte)
  print(body)
  </code></pre>
  
  <p>But this fails with :</p>
  
  <pre><code>Body is of type: &lt;class 'str'&gt;
  Traceback (most recent call last):
  File "C:/Users/David/Documents/Python/test2.py", line 31, in &lt;module&gt;
    body = myconvert(body,cte)
  File "C:/Users/David/Documents/Python/test2.py", line 6, in myconvert
    result = quopri.decodestring(encoded)
  File "C:\Python32\lib\quopri.py", line 164, in decodestring
    return a2b_qp(s, header=header)
  TypeError: 'str' does not support the buffer interface
  </code></pre>