def create_header(key, value, charset): """Create an appropriate email Header.""" maxlength = MAXHEADERLEN - (len(key) + 2) # Do not sent very short headers if maxlength < 10: raise TracError(_("Header length is too short")) email = None if isinstance(value, (tuple, list)): value, email = value if not isinstance(value, basestring): value = to_unicode(value) if not value: return email # when it matches mime-encoding, encode as mime even if only # ascii characters header = None if not _mime_encoding_re.search(value): try: tmp = value.encode('ascii') except UnicodeEncodeError: pass else: header = Header(tmp, 'ascii', maxlinelen=maxlength) if not header: header = Header(value.encode(charset.output_codec), charset, maxlinelen=maxlength) header = str(header) if email: header = header.replace('\\', r'\\').replace('"', r'\"') header = '"%s" <%s>' % (header, email) return header
def makeEncodedEmail(self, encoding_name, actual_encoding): email = self.factory.makeEmailMessage(body=self.high_characters) email.set_type('text/plain') email.set_charset(encoding_name) macroman = Header(self.high_characters, actual_encoding).encode() new_subject = macroman.replace(actual_encoding, encoding_name) email.replace_header('Subject', new_subject) return email
def create_header(key, value, charset): """Create an email Header. The `key` is always a string and will be converted to the appropriate `charset`. The `value` can either be a string or a two-element tuple where the first item is the name and the second item is the email address. See `set_header()` for a helper that sets a header directly on a message. """ maxlength = MAXHEADERLEN - (len(key) + 2) # Do not sent very short headers if maxlength < 10: raise TracError(_("Header length is too short")) email = None if isinstance(value, (tuple, list)): value, email = value if not isinstance(value, str): value = to_unicode(value) if not value: return email # when it matches mime-encoding, encode as mime even if only # ascii characters header = None if not _mime_encoding_re.search(value): try: tmp = value.encode('ascii') except UnicodeEncodeError: pass else: header = Header(tmp, 'ascii', maxlinelen=maxlength) if not header: header = Header(value.encode(charset.output_codec), charset, maxlinelen=maxlength) header = str(header) if email: header = header.replace('\\', r'\\').replace('"', r'\"') header = '"%s" <%s>' % (header, email) return header