title: python email encoding and decoding problems
body: <p>Basically I want to read all new emails from an inbox and put them in a database. The reason I use python is because it has <code>imaplib</code>, but I know nothing about it.</p>
  
  <p>Currently, I have something like this :</p>
  
  <pre><code>def primitive_get_text_blocks(email_message_instance):
      maintype = email_message_instance.get_content_maintype()
      if maintype == 'multipart':
          return_parts = ""
          for part in email_message_instance.get_payload():
              if part.get_content_maintype() == 'text':
                  return_parts+= " "+ part.get_payload()
          return return_parts
      elif maintype == 'text':
          return email_message_instance.get_payload()
      return ""
  
  fromField=con.escape(email_message["From"])
  contentField=con.escape(primitive_get_text_blocks(email_message))
  </code></pre>
  
  <p>primitive <code>get_text_blocks</code> is copy pasted from somewhere.
  The result is that I get database entries like this : </p>
  
  <pre><code>&lt;META http-equiv=3D"Content-Type" content=3D"text/html; charset=3DUTF-8"&gt;
  </code></pre>
  
  <p>From what I understand, that has something to do with being encoded in <code>utf-7</code>. So I changed to <code>get_payload(decode=True)</code>, but that gives me byte-arrays. If I append another <code>decode('utf-8')</code>, it sometimes crashes with errors like </p>
  
  <blockquote>
    <p>'codec error can't decode to ...'.</p>
  </blockquote>
  
  <p>I don't know how encodings work, I only want a unicode string with the body of my email. </p>
  
  <p>Why is there no simple <code>convert(charset from, charset to)</code>? How do I get a readable email body (and address?). I've discovered <a href="https://stackoverflow.com/questions/6969639/imap-fetch-encoding">IMAP Fetch Encoding</a> and using <code>decode_header</code> I got no further.</p>
  
  <p>--</p>
  
  <p>I assume encoding is the way bytes represent characters, so with that in mind, shouldn't decode take a byte array and spit out a string? and here on stack overflow I came across somebody claming it had something to do with beeing encoded with <code>utf-8</code> and <code>utf-7</code>. What does that even mean?</p>
  
  <p>I did google and there appear to be tons of duplicates but the answers they got didn't really help me out (I've tried most of them)</p>