如何在“发件人”电子邮件字符串中发送特殊字符(如注册符号)?例如。 Test® <test@hello.com> .我需要设置一些标题吗?
请您参考如下方法:
在 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 时, header 值显示时没有应用内容传输编码;然而,CTE 应用于实例本身,如调用 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
