From 192d03fd6816fb3c8a32ca8d2627d43cf7efe052 Mon Sep 17 00:00:00 2001 From: Son Nguyen Kim Date: Mon, 5 Sep 2022 15:38:04 +0200 Subject: [PATCH] make sure sl_formataddr always return str (#1269) --- app/email_utils.py | 5 +++-- tests/test_email_utils.py | 4 ++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/app/email_utils.py b/app/email_utils.py index b8769957e..0f25353cf 100644 --- a/app/email_utils.py +++ b/app/email_utils.py @@ -1466,6 +1466,7 @@ def get_verp_info_from_email(email: str) -> Optional[Tuple[VerpType, int]]: def sl_formataddr(name_address_tuple: Tuple[str, str]): - """Same as formataddr but use utf-8 encoding by default""" + """Same as formataddr but use utf-8 encoding by default and always return str (and never Header)""" name, addr = name_address_tuple - return formataddr((name, Header(addr, "utf-8"))) + # formataddr can return Header, make sure to convert to str + return str(formataddr((name, Header(addr, "utf-8")))) diff --git a/tests/test_email_utils.py b/tests/test_email_utils.py index 7ddf8360f..c6e4b2165 100644 --- a/tests/test_email_utils.py +++ b/tests/test_email_utils.py @@ -782,6 +782,10 @@ def test_add_header_multipart_with_invalid_part(): def test_sl_formataddr(): + # when the name part (first element in the tuple) is empty, formataddr() returns a Header + # this makes sure sl_formataddr always returns str + assert sl_formataddr(("", "a@b.c")) == "a@b.c" + assert sl_formataddr(("é", "è@ç.à")) == "=?utf-8?b?w6k=?= <è@ç.à>" # test that the same name-address can't be handled by the built-in formataddr with pytest.raises(UnicodeEncodeError):