diff --git a/pydantic/networks.py b/pydantic/networks.py index 5861850b4f..2a67198a6b 100644 --- a/pydantic/networks.py +++ b/pydantic/networks.py @@ -502,6 +502,9 @@ def _validate(cls, __input_value: NameEmail | str) -> NameEmail: return cls(name, email) def __str__(self) -> str: + if '@' in self.name: + return f'"{self.name}" <{self.email}>' + return f'{self.name} <{self.email}>' diff --git a/tests/test_networks.py b/tests/test_networks.py index 1a7d53425e..427c22547c 100644 --- a/tests/test_networks.py +++ b/tests/test_networks.py @@ -1,3 +1,4 @@ +import json from typing import Union import pytest @@ -867,3 +868,16 @@ class Model(BaseModel): assert exc_info.value.errors() == [ {'input': 1, 'loc': ('v',), 'msg': 'Input is not a valid NameEmail', 'type': 'name_email_type'} ] + + +@pytest.mark.skipif(not email_validator, reason='email_validator not installed') +def test_name_email_serialization(): + class Model(BaseModel): + email: NameEmail + + m = Model.model_validate({'email': '"name@mailbox.com" '}) + assert m.email.name == 'name@mailbox.com' + assert str(m.email) == '"name@mailbox.com" ' + + obj = json.loads(m.model_dump_json()) + Model(email=obj['email'])