开发者

Format email address with special character in display name

How can I send special character like registered symbol in a email's 'from' email string? E.g. Test® <test@hello.com>. Do I require to set some开发者_如何学Python headers?


In Python 3.6 or later, you can do it like this using the new 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

The header value is displayed with no Content Transfer Encoding applied when str is called on the email instance; however the CTE is applied in the instance itself, as can be seen by calling 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


email.header is used to handle unicodes used in headers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜