email utils (decode_header, get_header, parseaddr, formataddr) that useful while working with an email's parts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | from __future__ import unicode_literals
import email, email.header, email.utils
def decode_header(value):
l = email.header.decode_header(value)
l2 = []
for value, charset in l:
if charset:
value = value.decode(charset)
l2.append(value)
return ' '.join(l2)
def get_header(msg, header):
h = header.lower()
if msg.has_key(h):
return decode_header(msg[h])
return None
def parseaddr(msg, name):
'name = (from|to)'
value = msg[name]
name, addr = email.utils.parseaddr(value)
return decode_header(name), addr
def formataddr(name, addr):
encoding = 'utf-8'
pair = (name.encode(encoding), encoding)
h = str(email.header.make_header((pair,)))
return email.utils.formataddr((h, addr))
|