1

I'm creating an email using Python's email package (which is awesome!!).

I found out that it's better to encode the headers that have some weird chars in them (accents, etc), like the subject, using email.Header.

To do so, I'm doing the following, which is quite easy:

Header(value, 'UTF-8').encode()

It works great, but it also encode the fields that doesn't necessary require an encoding, lik

X-Mailer: My Service

that becomes

X-Mailer: =?utf-8?q?My_Service?=

I find it pretty useless in that case.

So my question: Is there a way to encode headers only when it will be useful?

I thought about playing with value.encode/decode() with a try/except, and call the Header().encode() function in the except, but I'm hoping there is a cleaner way to do so?

Cyril N.
  • 38,875
  • 36
  • 142
  • 243

1 Answers1

0

Ok, here's my best approach so far.

It's to try to decode the string using ascii charset. If it fails, we encode it using Header.encode(), otherwise, we leave it as is:

def encode_header(value):
    try:
        value.decode('ascii')
        return value
    except UnicodeDecodeError:
        return Header(value, 'UTF-8').encode()

I came to this solution thanks to this post: How to check if a string in Python is in ASCII?

Cyril N.
  • 38,875
  • 36
  • 142
  • 243