Alternatives:
-If you still need to process the broken MIME, use flanker.mime.fallback.FallbackMessage
-that relies on python parser in terms of fixing the broken MIME and forces broken
-encodings in bodies and headers, but beware that it can loose some information because
-of broken or unknown encodings.
+If you still need to process the broken MIME, use
+flanker.mime.fallback.FallbackMessage that relies on python parser in terms
+of fixing the broken MIME and forces broken encodings in bodies and headers,
+but beware that it can loose some information because of broken
+or unknown encodings.
Examples
-------
if RE_STATUS.match(v.strip()):
return v
+
def get_notification(message):
for part in message.walk():
- if part.headers.get('Content-Description', '').lower() == 'notification':
+ if part.headers.get('Content-Description',
+ '').lower() == 'notification':
return part.body
RE_STATUS = re.compile(r'\d\.\d+\.\d+', re.IGNORECASE)
+
class Result(object):
def __init__(self, score, status, notification, diagnostic_code):
self.score = score
self.status = status
self.notification = notification
self.diagnostic_code = diagnostic_code
-
-
from flanker.mime.message.headers.parametrized import fix_content_type
from flanker.mime.message.headers import WithParams
+
def multipart(subtype):
return MimePart(
container=Part(
is_root=True)
-def binary(maintype, subtype, body, filename=None, disposition=None, charset=None):
+def binary(maintype, subtype, body, filename=None,
+ disposition=None, charset=None):
return MimePart(
container=Body(
content_type=ContentType(maintype, subtype),
is_root=True)
-def attachment(content_type, body, filename=None, disposition=None, charset=None):
+def attachment(content_type, body, filename=None,
+ disposition=None, charset=None):
"""Smarter method to build attachments that detects the proper content type
and form of the message based on content type string, body and filename
of the attachment
def from_message(message):
return from_string(message.to_string())
-
from flanker.mime.message import errors
from flanker.utils import to_utf8, to_unicode
+
def convert_to_unicode(charset, value):
#in case of unicode we have nothing to do
if isinstance(value, unicode):
return to_unicode(value, charset=charset)
+
def _translate_charset(charset):
"""Translates crappy charset into Python analogue (if supported).
return 'utf-8'
return charset
-
class MimeError(Exception):
pass
+
class DecodingError(MimeError):
"""Thrown when there is an encoding error."""
pass
+
class EncodingError(MimeError):
"""Thrown when there is an decoding error."""
pass
import email
from flanker.mime.message.fallback.part import FallbackMimePart
+
def from_string(string):
return FallbackMimePart(email.message_from_string(string))
+
def from_python(message):
return FallbackMimePart(message)
# coding:utf-8
-import logging, regex as re
+import logging
+import regex as re
import email.quoprimime
import email.base64mime
#deal with unfolding
foldingWhiteSpace = re.compile(r"(\n\r?|\r\n?)(\s*)")
+
def unfold(value):
"""
Unfolding is accomplished by simply removing any CRLF
"""
try:
header = unfold(header)
- decoded = [] # decoded parts
+ decoded = [] # decoded parts
while header:
match = encodedWord.search(header)
try:
log.warning(
u"HEADER-DECODE-FAIL: ({0}) - b64encoded".format(
- b64encode(header)))
+ b64encode(header)))
except Exception:
log.exception("Failed to log exception")
return header
else:
raise errors.DecodingError(
"Unknown encoding: {0}".format(encoding))
-
-
-
# max length for a header line is 80 chars
# max recursion depth is 1000
# 80 * 1000 for header is too much for the system
-# so we allow just 100 lines for header
+# so we allow just 100 lines for header
MAX_HEADER_LENGTH = 8000
ADDRESS_HEADERS = ('From', 'To', 'Delivered-To', 'Cc', 'Bcc', 'Reply-To')
+
def to_mime(key, value):
if not value:
return ""
return to_utf8(value)
try:
return Header(
- value.encode("ascii"), "ascii", header_name=name).encode(
- splitchars=' ;,')
+ value.encode("ascii"), "ascii",
+ header_name=name).encode(splitchars=' ;,')
except UnicodeEncodeError:
if is_address_header(name, value):
return encode_address_header(name, value)
else:
return Header(
- to_utf8(value), "utf-8", header_name=name).encode(
- splitchars=' ;,')
+ to_utf8(value), "utf-8",
+ header_name=name).encode(splitchars=' ;,')
def encode_address_header(name, value):
value = value.encode("ascii")
return email.message._formatparam(name, value)
except Exception:
- value = Header(
- value.encode("utf-8"), "utf-8", header_name=key).encode(splitchars=' ;,')
+ value = Header(value.encode("utf-8"), "utf-8", header_name=key).encode(splitchars=' ;,')
return email.message._formatparam(name, value)
def encode_string(name, value):
try:
return Header(
- value.encode("ascii"), "ascii", header_name=name).encode(splitchars=' ;,')
+ value.encode("ascii"), "ascii",
+ header_name=name).encode(splitchars=' ;,')
except UnicodeEncodeError:
- return Header(
- value.encode("utf-8"), "utf-8", header_name=name).encode(splitchars=' ;,')
+ return Header(value.encode("utf-8"), "utf-8", header_name=name).encode(splitchars=' ;,')
def is_address_header(key, val):
"""
changed = [False]
+
def tracking_fn(key, val):
new_key, new_val = fn(key, val)
if new_val != val or new_key != key:
self.v = v
self.changed = True
-
def items(self):
"""
Returns header,val pairs in the preserved order.
"""
return list(self.iteritems())
-
def iteritems(self):
"""
Returns iterator header,val pairs in the preserved order.
"""
return self.v.iteritems()
-
def get(self, key, default=None):
"""
Returns header value (case-insensitive).
if encoded:
yield join_parameters(encoded)
+
def decode_charset(parameter):
"""Decodes things like:
"us-ascii'en'This%20is%20even%20more%20%2A%2A%2Afun%2A%2A%2A%20"
"""
return (ptype, key, value)
+
def is_quoted(part):
return get_value(part)[0] == '"'
+
def is_new_style(parameter):
return parameter[0] == 'new'
+
def is_old_style(parameter):
return parameter[0] == 'old'
+
def is_encoded(part):
return part[1][2] == '*'
+
def get_key(parameter):
if is_old_style(parameter):
return parameter[1].lower()
else:
return parameter[1][0].lower()
+
def get_value(parameter):
return parameter[2]
+
def join_parameters(parts):
joined = "".join(get_value(p) for p in parts)
for p in parts:
out.append(parse_header(header))
return out
+
def parse_header(header):
""" Accepts a raw header with name, colons and newlines
and returns it's parsed value
raise DecodingError("Non-ascii header name")
return name, parse_header_value(name, encodedword.unfold(val))
+
def parse_header_value(name, val):
if not is_pure_ascii(val):
if parametrized.is_parametrized(name, val):
else:
return val
+
def is_empty(line):
return line in ('\r\n', '\r', '\n')
RE_HEADER = regex.compile(r'^(From |[\041-\071\073-\176]+:|[\t ])')
+
def split(fp):
"""Read lines with headers until the start of body"""
lines = deque()
return normalize(pair[0].rstrip()), pair[1].lstrip()
else:
return (None, None)
-
def subtype(self):
return tuple.__getitem__(self, 0).split('/')[1]
-
def is_content_type(self):
return True
return self == 'message/feedback-report'
def is_delivery_report(self):
- return self == 'multipart/report'
+ return self == 'multipart/report'
def get_boundary(self):
return self.params.get("boundary")
return str.__new__(cls, *args, **kw)
def __clean(self):
- return self.replace('"','').replace("'", '')
+ return self.replace('"', '').replace("'", '')
def __hash__(self):
return hash(self.__clean())
def strip_replies(self):
return self.RE_RE.sub('', self)
-