From 657ee3c21c2eafff9953f9c4bed0033005eddb11 Mon Sep 17 00:00:00 2001 From: PrathamChoksi Date: Mon, 16 Nov 2026 16:40:34 +0530 Subject: [PATCH] fix: enforce the email local-part limit in UTF-8 octets --- src/validators/email.py | 4 ++-- tests/test_email.py | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/validators/email.py b/src/validators/email.py index 46cc5946..4f47ab23 100644 --- a/src/validators/email.py +++ b/src/validators/email.py @@ -60,8 +60,8 @@ def email( username_part, domain_part = value.rsplit("@", 1) - if len(username_part) > 64 or len(domain_part) > 253: - # ref: RFC 1034 and 5231 + if len(username_part.encode("utf-8")) > 64 or len(domain_part) > 253: + # ref: RFC 5321 section 4.5.3.1.1 (octets) and RFC 1034 return False if ipv6_address or ipv4_address: diff --git a/tests/test_email.py b/tests/test_email.py index 9b82eb46..7be2f3db 100644 --- a/tests/test_email.py +++ b/tests/test_email.py @@ -72,3 +72,17 @@ def test_rejects_newline_after_local_part(local_part: str): def test_returns_failed_validation_on_idna_mapped_lookalike_domain(domain_part: str): """Test returns failed validation on email domains that only IDNA 2003 mapping makes valid.""" assert isinstance(email(f"user@{domain_part}"), ValidationError) + + +@pytest.mark.parametrize("local_part", ["a" * 64, "\u00fc" * 32, "a" * 62 + "\u00fc"]) +def test_accepts_local_part_at_utf8_byte_limit(local_part: str): + """Test local parts at the 64-octet SMTP boundary.""" + assert len(local_part.encode("utf-8")) == 64 + assert email(f"{local_part}@example.com") is True + + +@pytest.mark.parametrize("local_part", ["a" * 65, "\u00fc" * 33, "a" * 63 + "\u00fc"]) +def test_rejects_local_part_over_utf8_byte_limit(local_part: str): + """Test that Unicode characters cannot exceed the SMTP octet limit.""" + assert len(local_part.encode("utf-8")) > 64 + assert isinstance(email(f"{local_part}@example.com"), ValidationError)