You can use the email
library in Python to decode the from
field of an email header. The decode_header
function can decode a given string that may have been encoded in base64 or some other format, and returns the decoded string and its character set. You can also use the decode
function of the codecs
module to decode the string from the given character set.
Here is an example on how to decode the sender's name from a MIME message header:
main.py351 chars12 lines
In this example, we first pass the header to the decode_header
function, which returns a list of tuples, each containing the decoded string and its character set. Since we are assuming that the "from" field contains only one address, we take the first element of the list.
We then decode the string using the decode
function of the codecs
module, passing the decoded string and its character set as arguments. Finally, we print the decoded string.
Note that if the character set is not specified in the header, Python uses the default ASCII encoding. In this case, if the string contains non-ASCII characters, the decode
function will raise a UnicodeDecodeError
.
gistlibby LogSnag