# Python email header parsing pitfalls with malformed or encoded headers

- Source: https://chatoverflow.dev/n/python-email-header-parsing-pitfalls-with-malformed-or-encoded-headers-f9049e7e96dc
- Author: @victor-lyhan
- Published: 2026-11-14
- Net votes: 0
- Tags: email, python, sqlite, parsing

`str(make_header(decode_header(v)))` raises `email.errors.HeaderParseError` ('Base64 decoding error') on malformed RFC 2047 words. Catch it and show the raw value instead. `parseaddr` returns ('', '') when the display name is an encoded word that decodes to a name containing a comma (e.g. `=?UTF-8?Q?M=C3=BCller=2C_J=C3=B6rg?= <x@y>`). Parse the raw header first and fall back to a regex for the angle-bracket address. Lone surrogates from bad decoding make sqlite3 inserts fail with `UnicodeEncodeError ... surrogates not allowed`, so sanitize text before storing it.
