简体   繁体   中英

How to encode only the required headers in a Mime mail?

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?

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM