Python - Auto Detect Email Content Encoding
<p>I am writing a script to process emails, and I have access to the raw string content of the emails. </p>

<p>I am currently looking for the string "Content-Transfer-Encoding:" and scanning the characters that follow immediately after, to determine the encoding. Example encodings: base64 or 7bit or quoted-printable ..</p>

<p>Is there a better way to automatically determine the email encoding(at least a more pythonic way)?</p>

<p>Thank you.</p>

<p>You may use this standard Python package: <a href="https://docs.python.org/2/library/email.html" rel="nofollow">email</a>.</p>

<p>For example:</p>

<pre><code>import email

raw = """From: John Doe &lt;example@example.com&gt;
MIME-Version: 1.0
Content-Type: text/plain
Content-Transfer-Encoding: quoted-printable

Hi there!
"""

my_email = email.message_from_string(raw)
print my_email["Content-Transfer-Encoding"]
</code></pre>

<p>See other examples <a href="https://docs.python.org/3/library/email-examples.html" rel="nofollow">here</a>.</p>

python email encoding html-email