格式化带特殊字符的邮箱地址显示名称
我想知道怎么在邮件的发件人地址中发送像注册商标这样的特殊字符,比如 Test® <test@hello.com>
。我需要设置一些邮件头吗?
2 个回答
0
email.header
是用来处理邮件头部中使用的 Unicode 字符的工具。
1
在Python 3.6或更高版本中,你可以使用新的EmailMessage/Policy API来实现这个功能。
>>> from email.message import EmailMessage
>>> from email.headerregistry import Address
>>> em = EmailMessage()
>>> from_ = Address(display_name="Test®", username="test", domain="hello.com")
>>> em['from'] = from_
>>> em['to'] = Address('JohnD', 'John.Doe', 'example.com')
>>> em.set_content('Hello world')
>>> print(em)
to: JohnD <John.Doe@example.com>
from: Test® <test@hello.com>
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit
MIME-Version: 1.0
Hello world
当你对邮件实例调用str
时,头部的值会直接显示,没有任何内容传输编码(Content Transfer Encoding)被应用;不过在实例内部,内容传输编码是有应用的,这一点可以通过调用EmailMessage.as_string
来查看:
>>> print(em.as_string())
to: JohnD <John.Doe@example.com>
from: =?utf-8?q?Test=C2=AE?= <test@hello.com>
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit
MIME-Version: 1.0
Hello world