Changes between Version 4 and Version 6 of Ticket #36746


Ignore:
Timestamp:
Nov 25, 2025, 12:53:32 PM (2 weeks ago)
Author:
Mike Edmunds
Comment:

Legend:

Unmodified
Added
Removed
Modified
  • Ticket #36746

    • Property Status assignedclosed
    • Property Resolutionneedsinfo
  • Ticket #36746 – Description

    v4 v6  
    11When parsing invalid email addresses (such as 'to@') in the SMTP backend's prep_address() method, Python's email parser raises an IndexError instead of the expected ValueError. This causes the test test_avoids_sending_to_invalid_addresses to fail.
    22
    3 **Steps to reproduce:
     3**Steps to reproduce:**
    441. Run Django's test suite: `./runtests.py mail.tests.SMTPBackendTests.test_avoids_sending_to_invalid_addresses`
    552. The test fails with IndexError when trying to parse 'to@'
    66
    7 **Root cause:
     7**Root cause:**
    88The prep_address() method at line 172 in `django/core/mail/backends/smtp.py` directly calls `AddressHeader.value_parser(address)` without exception handling. When parsing malformed addresses like 'to@', Python's email parser first raises HeaderParseError, then during exception handling attempts to parse the address differently, which leads to an IndexError when trying to access `value[0]` on an empty string.
    99
    10 **Proposed solution:
     10**Proposed solution:**
    1111Wrap the `AddressHeader.value_parser()` call in a try-except block to catch `HeaderParseError`, `IndexError`, and `ValueError` exceptions, converting them to `ValueError` with an appropriate message. This matches the pattern already used in the deprecated `sanitize_address()` function in `django/core/mail/message.py` (line 115).
    1212
    13 **Expected behavior:
     13**Expected behavior:**
    1414The prep_address() method should catch parsing exceptions and raise ValueError with message "Invalid address" for invalid addresses, matching the test's expectation.
    1515
    16 **Actual behavior:
     16**Actual behavior:**
    1717IndexError: string index out of range is raised from Python's email._header_value_parser when parsing addresses like 'to@'.
    1818
    19 **Error traceback:
     19**Error traceback:**
    2020{{{
    2121ERROR: test_avoids_sending_to_invalid_addresses (mail.tests.SMTPBackendTests.test_avoids_sending_to_invalid_addresses) [<object object at 0x12d0aff70>] (email_address='to@')
Back to Top