How to handle UTF8 string from Pythons imaplib
<p>Python imaplib sometimes returns strings that looks like this:</p>

<pre><code>=?utf-8?Q?Repertuar_wydarze=C5=84_z_woj._Dolno=C5=9Bl=C4=85skie?=
</code></pre>

<p>What is the name for this notation?</p>

<p>How can I decode (or should I say encode?) it to UTF8?</p>

<p><strong>In short:</strong></p>

<pre><code>&gt;&gt;&gt; from email.header import decode_header
&gt;&gt;&gt; msg = decode_header('=?utf-8?Q?Repertuar_wydarze=C5=84_z_woj._Dolno=C5=9Bl=C4=85skie?=')[0][0].decode('utf-8')
&gt;&gt;&gt; msg
'Repertuar wydarze\u0144 z woj. Dolno\u015bl\u0105skie'
</code></pre>

<p>My computer doesn't show the polish characters, but they should appear in yours (locales etc.)</p>

<hr>

<p><strong>Explained:</strong></p>

<p>Use the <code>email.header</code> decoder:</p>

<pre><code>&gt;&gt;&gt; from email.header import decode_header
&gt;&gt;&gt; value = decode_header('=?utf-8?Q?Repertuar_wydarze=C5=84_z_woj._Dolno=C5=9Bl=C4=85skie?=')
&gt;&gt;&gt; value
[(b'Repertuar wydarze\xc5\x84 z woj. Dolno\xc5\x9bl\xc4\x85skie', 'utf-8')]
</code></pre>

<p>That will return a list with the decoded header, usually containing one tuple with the decoded message and the encoding detected (sometimes more than one pair).</p>

<pre><code>&gt;&gt;&gt; msg, encoding = decode_header('=?utf-8?Q?Repertuar_wydarze=C5=84_z_woj._Dolno=C5=9Bl=C4=85skie?=')[0]
&gt;&gt;&gt; msg
b'Repertuar wydarze\xc5\x84 z woj. Dolno\xc5\x9bl\xc4\x85skie'
&gt;&gt;&gt; encoding
'utf-8'
</code></pre>

<p>And finally, if you want <code>msg</code> as a normal utf-8 string, use the bytes <code>decode</code> method:</p>

<pre><code>&gt;&gt;&gt; msg = msg.decode('utf-8')
&gt;&gt;&gt; msg
'Repertuar wydarze\u0144 z woj. Dolno\u015bl\u0105skie'
</code></pre>

python utf-8 imaplib