def formataddr(pair): """ This code is copy of python2 email.utils.formataddr. Takes a 2-tuple of the form (realname, email_address) and returns RFC2822-like string. Does not encode non-ascii realname. Python3 email.utils.formataddr do encode realname. """ name, address = pair if name: quotes = '' if specialsre.search(name): quotes = '"' name = escapesre.sub(r'\\\g<0>', name) return '%s%s%s <%s>' % (quotes, name, quotes, address) return address
def nice_sender_header(name, address, charset): # construct an address header so it's as human-readable as possible # even in the presence of a non-ASCII name part if not name: return address try: encname = b2s(name.encode('ASCII')) except UnicodeEncodeError: # use Header to encode correctly. encname = Header(name, charset=charset).encode() # the important bits of formataddr() if specialsre.search(encname): encname = '"%s"' % escapesre.sub(r'\\\g<0>', encname) # now format the header as a string - don't return a Header as anonymous # headers play poorly with Messages (eg. won't get wrapped properly) return '%s <%s>' % (encname, address)
def nice_sender_header(name, address, charset): # construct an address header so it's as human-readable as possible # even in the presence of a non-ASCII name part if not name: return address try: encname = name.encode('ASCII') except UnicodeEncodeError: # use Header to encode correctly. encname = Header(name, charset=charset).encode() # the important bits of formataddr() if specialsre.search(encname): encname = '"%s"'%escapesre.sub(r'\\\g<0>', encname) # now format the header as a string - don't return a Header as anonymous # headers play poorly with Messages (eg. won't get wrapped properly) return '%s <%s>'%(encname, address)
def py32_formataddr(pair): """ HACK: Copied from 3.2 standard lib: 3.3 auto MIME-encodes non-ASCII names, and offers no way to disable this new/differing functionality; The inverse of parseaddr(), this takes a 2-tuple of the form (realname, email_address) and returns the string value suitable for an RFC 2822 From, To or Cc header. If the first element of pair is false, then the second element is returned unmodified. """ name, address = pair if name: quotes = '' if specialsre.search(name): quotes = '"' name = escapesre.sub(r'\\\g<0>', name) return '%s%s%s <%s>' % (quotes, name, quotes, address) return address