How to send emails with names in headers from Python
<p>I need to send nice-looking emails from Python with address headers that contain names - somehow something that never pops up in tutorials.</p>

<p>I'm using email.mime.text.MIMEText() to create the email, but setting <code>msg['To'] = 'Ã¡ &lt;x@y.cz&gt;'</code> rather than utf8-encoding only the name part, will utf8-encode the whole header value, which of course fails miserably. How to do this correctly?</p>

<p>I have found a sort-of solution <a href="http://stackoverflow.com/questions/10551933/python-email-module-form-header-from-with-some-unicode-name-email">Python email module: form header &quot;From&quot; with some unicode name + email</a> but it feels hard to accept such a hack, since there does seem to be some support for handling this automatically in Python's email package in email.headerregistry which should be used automatically as far as I can see, but it doesn't happen.</p>

<p>You have to use the right policy from <code>email.policy</code> to get the correct behaviour.</p>

<h2>Wrong Policy</h2>

<p><a href="https://docs.python.org/3.5/library/email.message.html#email.message.Message" rel="nofollow"><code>email.message.Message</code></a> will use <code>email.policy.Compat32</code> by default. That one was designed for backward-compatibility wih older Python versions and does the wrong thing:</p>

<pre><code>&gt;&gt;&gt; msg = email.message.Message(policy=email.policy.Compat32())
&gt;&gt;&gt; msg['To'] = 'Å¡Å¡Å¡Å¡Å¡ &lt;ssss@example.com&gt;'
&gt;&gt;&gt; msg.as_bytes()
b'To: =?utf-8?b?xaHFocWhxaHFoSA8c3Nzc0BleGFtcGxlLmNvbT4=?=\n\n'
</code></pre>

<h2>Correct Policy</h2>

<p><a href="https://docs.python.org/3.5/library/email.policy.html#email.policy.EmailPolicy" rel="nofollow"><code>email.policy.EmailPolicy</code></a> will do what you want:</p>

<pre><code>&gt;&gt;&gt; msg = email.message.Message(policy=email.policy.EmailPolicy())
&gt;&gt;&gt; msg['To'] = 'Å¡Å¡Å¡Å¡Å¡ &lt;ssss@example.com&gt;'
&gt;&gt;&gt; msg.as_bytes()
b'To: =?utf-8?b?xaHFocWhxaHFoQ==?= &lt;ssss@example.com&gt;\n\n'
</code></pre>

<h2>Python 2.7</h2>

<p>With older Python versions (eg 2.7), you have to use the "hack" as you called it:</p>

<pre><code>&gt;&gt;&gt; msg = email.message.Message()
&gt;&gt;&gt; msg['To'] = email.header.Header(u'Å¡Å¡Å¡Å¡Å¡').encode() + ' &lt;ssss@example.com&gt;'
&gt;&gt;&gt; msg.as_string()
'To: =?utf-8?b?xaHFocWhxaHFoQ==?= &lt;ssss@example.com&gt;\n\n'
</code></pre>

python python-3.x email