i need decode "from:", sender from utf 8 and base64 in python

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.py
import email.header
import codecs

# Assuming that "header" variable contains the desired header (in bytes format)
decoded_header = email.header.decode_header(header)[0]

# Decoding the header string from the given character set
decoded_string = codecs.decode(decoded_header[0], decoded_header[1])

# Printing the decoded string
print(decoded_string)
351 chars
12 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.

related categories

gistlibby LogSnag