[英]How to encode only the required headers in a Mime mail?
I'm creating an email using Python's email
package (which is awesome!!). 我正在使用Python的
email
包创建电子邮件(太棒了!)。
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 . 我发现最好使用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? 我曾考虑过使用try / except来与
value.encode/decode()
一起玩,并在except中调用Header().encode()
函数,但我希望有一种更干净的方法吗?
Ok, here's my best approach so far. 好的,这是到目前为止我最好的方法。
It's to try to decode the string using ascii
charset. 尝试使用
ascii
字符集解码字符串。 If it fails, we encode it using Header.encode()
, otherwise, we leave it as is: 如果失败,则使用
Header.encode()
对其进行编码,否则,将其Header.encode()
:
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? 由于这篇文章,我来到了这个解决方案: 如何检查Python中的字符串是否为ASCII?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.