last day (15 days later) » 

5:08 PM
0
Q: how can I determine whether an email header is base64 encoded

PurpleVermontUsing the email.header package, I can do the_text,the_charset = decode_header(inputText) to get the character set of the email header, where the inputText was retrieved by a command like inputText = msg.get('From') to use the From: header as an example. in order to extract the header enc...

 
decode_header decodes the header from base64 or quoted printable encoding as needed; the the_charset component is the codec declared in the header.
 
@MartijnPieters That was how I understood decode_header, but for other reasons I still need to know if the header had been base64 encoded or not. Can I get that info by the method I suggested? Or is there an easier way?
 
I'm not sure I understand what you are looking for. Do you want to know if the header uses the Encoded-Word syntax, and if so, if base64 or quoted-printable was used?
 
@MartijnPieters yes
 
Note that a header can include multiple encoded-word sections, and that each could potentially use a different encoding! Did you want the whole list in that case?
 
5:08 PM
Looking at the Wiki @MartijnPieters quoted above, it looks like maybe I should just parse the Q or B out of the original header manually, unless Python provides ready access to this.
I had not thought about the possibility of multiple encoded word sections. Could they have different charsets as well? (In that case, what would decode_header return as its second return value?
 
5:25 PM
The decode_header() function returns a list of tuples.
So for each entry you get (text, codec).
but the function merges sections if they use the same characterset.
So if you have section_using_utf8 CRLF section_using_utf8, the function merges those two sections.
But if different encodings are used then you get separate tuples.
You could get [('first text', 'utf-8'), ('second text', 'latin-1')] for example.
 
Thanks. Looks like if I just want to extract all the charsets, then, I'd want something like this:
def get_header_charsets(header_text):
"""Return the list of charsets used in the specified header"""
return ([charset or "None" for text,charset in decode_header(header_text)])
Any chance you could point me to a source of sample valid headers that include multiple encodings?
(I'm not new to Python but I've been programming in java for quite some time, so my Python is pretty rusty and probably unpythonic ;-) )
 
 
2 hours later…
8:01 PM
I have no samples, sorry. But technically it is possible, it'd be a valid header.
 

last day (15 days later) »