使用特殊字符的显示名称格式化电子邮件地址

3

如何在电子邮件的“发件人”字符串中发送特殊字符,例如注册符号?例如:Test® <test@hello.com>。我需要设置一些标头吗?

2个回答

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时,标题值将显示为未应用任何内容传输编码;然而,在实例本身中应用了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

0

email.header 用于处理邮件头中使用的 Unicode 编码。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接