From d96bcfe6fb1f6f746f2b40a9998547b630221c9c Mon Sep 17 00:00:00 2001 From: Maxim Vladimirsky Date: Wed, 16 Jul 2014 10:20:52 +0400 Subject: [PATCH] Make FallbackMimePart interface match with MimePart To achieve that common functionality has been extracted to RichPartMixin that is mixed to both classes. --- flanker/mime/bounce.py | 6 + flanker/mime/message/fallback/part.py | 180 +++----- flanker/mime/message/part.py | 421 ++++++++++--------- flanker/mime/message/utils.py | 1 + tests/mime/bounce_tests.py | 12 +- tests/mime/message/fallback/fallback_test.py | 85 +++- tests/mime/message/part_test.py | 45 +- 7 files changed, 412 insertions(+), 338 deletions(-) diff --git a/flanker/mime/bounce.py b/flanker/mime/bounce.py index 8deacb0..055c6d3 100644 --- a/flanker/mime/bounce.py +++ b/flanker/mime/bounce.py @@ -65,3 +65,9 @@ class Result(object): self.status = status self.notification = notification self.diagnostic_code = diagnostic_code + + def __repr__(self): + return (u'bounce.Result(status={}, score={}, notification={},' + u' diag_code={})'.format(self.status, self.score, + self.notification, + self.diagnostic_code)) diff --git a/flanker/mime/message/fallback/part.py b/flanker/mime/message/fallback/part.py index d49e257..598dcc6 100644 --- a/flanker/mime/message/fallback/part.py +++ b/flanker/mime/message/fallback/part.py @@ -1,158 +1,109 @@ import logging import email +from flanker.mime.message.part import ReachPartMixin from flanker.mime.message.scanner import ContentType from flanker.mime.message import utils, charsets, headers from flanker.mime.message.headers import parametrized log = logging.getLogger(__name__) -class FallbackMimePart(object): - def __init__(self, python_message): - self.m = python_message - self._is_root = False - - def is_body(self): - return (self.content_type.format_type == 'text' or - self.content_type.format_type == 'message') - - def is_root(self): - return self._is_root - - def set_root(self, value): - self._is_root = value +class FallbackMimePart(ReachPartMixin): - def append(self, message): - self.m.attach( - FallbackMimePart( - email.message_from_string( - message.to_string()))) - - def remove_headers(self, *headers): - for header in headers: - if header in self.headers: - del self.headers[header] - - def is_bounce(self): - return False + def __init__(self, python_message): + ReachPartMixin.__init__(self, is_root=False) + self._m = python_message @property - def bounce(self): - return None - - def to_python_message(self): - return self.m - - def get_attached_message(self): - """ - Returns attached message if found, None otherwize - """ - try: - for part in self.walk(with_self=True): - if part.content_type == 'message/rfc822': - for p in part.walk(): - return p - except Exception: - log.exception("Failed to get attached message") - return None - - def walk(self, with_self=False, skip_enclosed=False): - if with_self: - yield self - - if self.content_type.is_multipart(): - for p in self.parts: - yield p - for x in p.walk(False, skip_enclosed=skip_enclosed): - yield x + def size(self): + if not self._m.is_multipart(): + return len(self._m.get_payload(decode=False)) + else: + return sum(p.size for p in self.parts) - elif self.content_type.is_message_container() and not skip_enclosed: - yield self.enclosed - for p in self.enclosed.walk(False): - yield p + @property + def headers(self): + return FallbackHeaders(self._m) @property def content_type(self): return ContentType( - self.m.get_content_maintype(), - self.m.get_content_subtype(), - dict(self.m.get_params() or [])) + self._m.get_content_maintype(), + self._m.get_content_subtype(), + dict(self._m.get_params() or [])) @property - def charset(self): - return self.content_type.params.get('charset', 'ascii') + def content_disposition(self): + try: + return parametrized.decode(self._m.get('Content-Disposition', '')) + except: + return None, {} @property - def headers(self): - return FallbackHeaders(self.m) + def content_encoding(self): + return self._m.get('Content-Transfer-Encoding') + + @content_encoding.setter + def content_encoding(self, value): + pass # FIXME Not implement @property def body(self): - if not self.m.is_multipart(): + if self.content_type.is_delivery_status(): + body = self._m.get_payload(decode=True) + if body: + return body + return "\r\n".join(str(p) for p in self._m.get_payload()) + if not self._m.is_multipart(): return charsets.convert_to_unicode( - self.charset, - self.m.get_payload(decode=True)) + self.charset, self._m.get_payload(decode=True)) @body.setter def body(self, value): - if not self.m.is_multipart(): - return self.m.set_payload( - value.encode('utf-8'), 'utf-8') + if not self._m.is_multipart(): + self._m.set_payload(value.encode('utf-8'), 'utf-8') @property - def parts(self): - if self.m.is_multipart(): - return [FallbackMimePart(p) for p in self.m.get_payload() if p] - else: - return [] + def charset(self): + return self.content_type.get_charset() - @property - def enclosed(self): - if self.content_type == 'message/rfc822': - return FallbackMimePart(self.m.get_payload()[0]) + @charset.setter + def charset(self, value): + pass # FIXME Not implement - @property - def size(self): - if not self.m.is_multipart(): - return len(self.m.get_payload(decode=False)) - else: - return sum(p.size for p in self.parts) + def to_string(self): + return utils.python_message_to_string(self._m) - @property - def content_encoding(self): - return self.m.get('Content-Transfer-Encoding') + def to_stream(self, out): + out.write(self.to_string()) - @content_encoding.setter - def content_encoding(self, value): - pass + def was_changed(self): + return False # FIXME Not implement - @property - def content_disposition(self): - try: - return parametrized.decode( - self.m.get('Content-Disposition', '')) - except: - return (None, {}) + def to_python_message(self): + return self._m - def to_string(self): - return utils.python_message_to_string(self.m) + def append(self, *messages): + for m in messages: + part = FallbackMimePart(email.message_from_string(m.to_string())) + self._m.attach(part) - def to_stream(self, out): - out.write(self.to_string()) + @property + def parts(self): + if self._m.is_multipart(): + return [FallbackMimePart(p) for p in self._m.get_payload() if p] + else: + return [] - def is_attachment(self): - return self.content_disposition[0] == 'attachment' + @property + def enclosed(self): + if self.content_type == 'message/rfc822': + return FallbackMimePart(self._m.get_payload()[0]) - def is_inline(self): - return self.content_disposition[0] == 'inline' + def enclose(self, message): + pass # FIXME Not implemented - def is_delivery_notification(self): - ctype = self.content_type - return ctype == 'multipart/report'\ - and ctype.params.get('report-type') == 'delivery-status' - def __str__(self): - return "FallbackMimePart" def try_decode(key, value): if isinstance(value, (tuple, list)): @@ -167,6 +118,7 @@ def try_decode(key, value): else: return "" + class FallbackHeaders(object): def __init__(self, message): diff --git a/flanker/mime/message/part.py b/flanker/mime/message/part.py index a07533a..f979d68 100644 --- a/flanker/mime/message/part.py +++ b/flanker/mime/message/part.py @@ -3,22 +3,21 @@ import email.encoders import logging import mimetypes import imghdr -import base64 -import quopri - from contextlib import closing from cStringIO import StringIO -from os import path +from os import path from email.mime import audio from flanker.utils import is_pure_ascii from flanker.mime import bounce from flanker.mime.message import headers, charsets -from flanker.mime.message.headers import WithParams, ContentType, MessageId, Subject +from flanker.mime.message.headers import (WithParams, ContentType, MessageId, + Subject) from flanker.mime.message.headers.parametrized import fix_content_type from flanker.mime.message.errors import EncodingError, DecodingError + log = logging.getLogger(__name__) CTE = WithParams('7bit', {}) @@ -179,13 +178,192 @@ class Part(object): return True -class MimePart(object): - def __init__(self, container, parts=None, enclosed=None, is_root=False): +class ReachPartMixin(object): - self._container = container + def __init__(self, is_root=False): self._is_root = is_root self._bounce = None + @property + def message_id(self): + return MessageId.from_string(self.headers.get('Message-Id', '')) + + @message_id.setter + def message_id(self, value): + if not MessageId.is_valid(value): + raise ValueError("invalid message id format") + self.headers['Message-Id'] = "<{0}>".format(value) + + @property + def subject(self): + return self.headers.get('Subject', '') + + @property + def clean_subject(self): + """ + Subject without re, fw, fwd, HA prefixes + """ + return Subject(self.subject).strip_replies() + + @property + def references(self): + """ + Returns a list of message ids referencing the message in accordance to + the Jamie Zawinski threading algorithm. + + See http://www.jwz.org/doc/threading.html for details. + """ + refs = list(MessageId.scan(self.headers.get('References', ''))) + if not refs: + reply = MessageId.from_string(self.headers.get('In-Reply-To', '')) + if reply: + refs.append(reply[0]) + return refs + + @property + def detected_file_name(self): + """ + Detects file name based on content type or part name. + """ + ctype = self.content_type + file_name = ctype.params.get('name', '') or ctype.params.get('filename', '') + + value, params = self.content_disposition + if value == 'attachment': + file_name = params.get('filename', '') or file_name + + # filenames can be presented as tuples, like: + # ('us-ascii', 'en-us', 'image.jpg') + if isinstance(file_name, tuple) and len(file_name) == 3: + # encoding permissible to be empty + encoding = file_name[0] + if encoding: + file_name = file_name[2].decode(encoding) + else: + file_name = file_name[2] + + file_name = headers.mime_to_unicode(file_name) + return file_name + + @property + def detected_format(self): + return self.detected_content_type.format_type + + @property + def detected_subtype(self): + return self.detected_content_type.subtype + + @property + def detected_content_type(self): + """ + Returns content type based on the body content, the file name and the + original content type provided inside the message. + """ + return adjust_content_type(self.content_type, + filename=self.detected_file_name) + + def is_body(self): + return (not self.detected_file_name and + (self.content_type.format_type == 'text' or + self.content_type.format_type == 'message')) + + def is_root(self): + return self._is_root + + def set_root(self, val): + self._is_root = bool(val) + + def walk(self, with_self=False, skip_enclosed=False): + """ + Returns iterator object traversing through the message parts. If the + top level part needs to be included then set the `with_self` to `True`. + If the parts of the enclosed messages should not be included then set + the `skip_enclosed` parameter to `True`. + """ + + if with_self: + yield self + + if self.content_type.is_multipart(): + for p in self.parts: + yield p + for x in p.walk(with_self=False, skip_enclosed=skip_enclosed): + yield x + + elif self.content_type.is_message_container() and not skip_enclosed: + yield self.enclosed + for p in self.enclosed.walk(with_self=False): + yield p + + def is_attachment(self): + return self.content_disposition[0] == 'attachment' + + def is_inline(self): + return self.content_disposition[0] == 'inline' + + def is_delivery_notification(self): + """ + Tells whether a message is a system delivery notification. + """ + content_type = self.content_type + return (content_type == 'multipart/report' + and content_type.params.get('report-type') == 'delivery-status') + + def get_attached_message(self): + """ + Returns attached message if found, `None` otherwise. + """ + try: + for part in self.walk(with_self=True): + if part.content_type == 'message/rfc822': + for p in part.walk(): + return p + except Exception: + log.exception("Failed to get attached message") + return None + + def remove_headers(self, *header_names): + """ + Removes all passed headers name in one operation. + """ + for header_name in header_names: + if header_name in self.headers: + del self.headers[header_name] + + @property + def bounce(self): + """ + If the message is NOT bounce, then `None` is returned. Otherwise + it returns a bounce object that provides the values: + * score - a value between 0 and 1, where 0 means that the message is + definitely not a bounce, and 1 means that is definitely a + bounce; + * status - delivery status; + * notification - human readable description; + * diagnostic_code - smtp diagnostic codes; + + Can raise MimeError in case if MIME is screwed. + """ + if not self._bounce: + self._bounce = bounce.detect(self) + return self._bounce + + def is_bounce(self, probability=0.3): + """ + Determines whether the message is a bounce message based on + given probability. 0.3 is a good conservative base. + """ + return self.bounce.score > probability + + def __str__(self): + return "({0})".format(self.content_type) + + +class MimePart(ReachPartMixin): + + def __init__(self, container, parts=None, enclosed=None, is_root=False): + ReachPartMixin.__init__(self, is_root) + self._container = container self.parts = parts or [] self.enclosed = enclosed @@ -259,90 +437,10 @@ class MimePart(object): self.headers['Content-Type'].params['charset'] = charset self.headers.changed = True - @property - def message_id(self): - return MessageId.from_string(self.headers.get('Message-Id', '')) - - @message_id.setter - def message_id(self, value): - if not MessageId.is_valid(value): - raise ValueError("invalid message id format") - self.headers['Message-Id'] = "<{0}>".format(value) - - @property - def subject(self): - return self.headers.get('Subject', '') - - @property - def clean_subject(self): - """ - Subject without re, fw, fwd, HA prefixes - """ - return Subject(self.subject).strip_replies() - - @property - def references(self): - """ - Retunrs message-ids referencing the message - in accordance to jwz threading algo - """ - refs = list(MessageId.scan(self.headers.get('References', ''))) - if not refs: - reply = MessageId.from_string(self.headers.get('In-Reply-To', '')) - if reply: - refs.append(reply[0]) - return refs - - @property - def detected_format(self): - return self.detected_content_type.format_type - - @property - def detected_subtype(self): - return self.detected_content_type.subtype - - @property - def detected_content_type(self): - """Returns content type based on the body - content, file name and original content type - supplied inside the message + def to_string(self): """ - return adjust_content_type( - self.content_type, filename=self.detected_file_name) - - @property - def detected_file_name(self): - """Detects file name based on content type - or part name + Returns a MIME representation of the message. """ - ctype = self.content_type - file_name = ctype.params.get('name', '') or ctype.params.get('filename', '') - - cdisp = self.content_disposition - if cdisp.value == 'attachment': - file_name = cdisp.params.get('filename', '') or file_name - - # filenames can be presented as tuples, like: - # ('us-ascii', 'en-us', 'image.jpg') - if isinstance(file_name, tuple) and len(file_name) == 3: - # encoding permissible to be empty - encoding = file_name[0] - if encoding: - file_name = file_name[2].decode(encoding) - else: - file_name = file_name[2] - - file_name = headers.mime_to_unicode(file_name) - return file_name - - def is_root(self): - return self._is_root - - def set_root(self, val): - self._is_root = bool(val) - - def to_string(self): - """ returns MIME representation of the message""" # this optimisation matters *A LOT* # we submit the original string, # no copying, no alternation, yeah! @@ -354,19 +452,48 @@ class MimePart(object): return out.getvalue() def to_stream(self, out): - """ serialzes the message using file like object """ + """ + Serializes the message using a file like object. + """ if not self.was_changed(): out.write(self._container.read_message()) else: try: original_position = out.tell() - self.to_stream_when_changed(out) + self._to_stream_when_changed(out) except DecodingError: out.seek(original_position) out.write(self._container.read_message()) + def was_changed(self): + if self._container.headers_changed(): + return True + + if self.content_type.is_singlepart(): + if self._container.body_changed(): + return True + return False + + elif self.content_type.is_multipart(): + return any(p.was_changed() for p in self.parts) + + elif self.content_type.is_message_container(): + return self.enclosed.was_changed() + + def to_python_message(self): + return email.message_from_string(self.to_string()) + + def append(self, *messages): + for m in messages: + self.parts.append(m) + m.set_root(False) + + def enclose(self, message): + self.enclosed = message + message.set_root(False) + - def to_stream_when_changed(self, out): + def _to_stream_when_changed(self, out): ctype = self.content_type @@ -403,114 +530,6 @@ class MimePart(object): elif ctype.is_message_container(): self.enclosed.to_stream(out) - def was_changed(self): - if self._container.headers_changed(): - return True - - if self.content_type.is_singlepart(): - if self._container.body_changed(): - return True - return False - - elif self.content_type.is_multipart(): - return any(p.was_changed() for p in self.parts) - - elif self.content_type.is_message_container(): - return self.enclosed.was_changed() - - def walk(self, with_self=False, skip_enclosed=False): - """ Returns iterator object traversing through the message parts, - if you want to include the top level part into the iteration, use - 'with_self' parameter. If you don't want to include parts of - enclosed messages, use 'skip_enclosed' parameter. Each part itself - provides headers, content_type and body members. - """ - if with_self: - yield self - - if self.content_type.is_multipart(): - for p in self.parts: - yield p - for x in p.walk(False, skip_enclosed=skip_enclosed): - yield x - - elif self.content_type.is_message_container() and not skip_enclosed: - yield self.enclosed - for p in self.enclosed.walk(False): - yield p - - def is_attachment(self): - return self.content_disposition.value == 'attachment' - - def is_body(self): - return (not self.detected_file_name and - (self.content_type.format_type == 'text' or - self.content_type.format_type == 'message')) - - def is_inline(self): - return self.content_disposition.value == 'inline' - - def is_delivery_notification(self): - """ Tells whether a message is a system delivery notification """ - ctype = self.content_type - return ctype == 'multipart/report'\ - and ctype.params.get('report-type') == 'delivery-status' - - def get_attached_message(self): - """ Returns attached message if found, None otherwize""" - try: - for part in self.walk(with_self=True): - if part.content_type == 'message/rfc822': - for p in part.walk(): - return p - except Exception: - log.exception("Failed to get attached message") - return None - - def remove_headers(self, *headers): - """Removes all passed headers name in one operation""" - for header in headers: - if header in self.headers: - del self.headers[header] - - def to_python_message(self): - return email.message_from_string(self.to_string()) - - @property - def bounce(self): - """ If the message is bounce, retuns bounce object that - provides the values: - - score - between 0 and 1 - status - delivery status - notification - human readable description - diagnostic_code - smtp diagnostic codes - - Can raise MimeError in case if MIME is screwed - """ - if not self._bounce: - self._bounce = bounce.detect(self) - return self._bounce - - def is_bounce(self, threshold=0.3): - """ - Determines whether the message is a bounce message based on - given threshold. 0.3 is a good conservative base. - """ - return self.bounce.score > threshold - - def enclose(self, message): - self.enclosed = message - message.set_root(False) - - def append(self, *messages): - for m in messages: - self.parts.append(m) - m.set_root(False) - - def __str__(self): - return "({0})".format(self.content_type) - def decode_body(content_type, content_encoding, body): # decode the transfer encoding diff --git a/flanker/mime/message/utils.py b/flanker/mime/message/utils.py index 1c47055..4897c9f 100644 --- a/flanker/mime/message/utils.py +++ b/flanker/mime/message/utils.py @@ -2,6 +2,7 @@ from cStringIO import StringIO from contextlib import closing from email.generator import Generator + def python_message_to_string(msg): """Converts python message to string in a proper way""" with closing(StringIO()) as fp: diff --git a/tests/mime/bounce_tests.py b/tests/mime/bounce_tests.py index cb9be82..8fcf83d 100644 --- a/tests/mime/bounce_tests.py +++ b/tests/mime/bounce_tests.py @@ -1,12 +1,18 @@ -from nose.tools import * -from .. import * +from nose.tools import ok_, eq_, assert_false from flanker.mime import create +from tests import BOUNCE, SIGNED + def test_bounce_analyzer_on_bounce(): bm = create.from_string(BOUNCE) ok_(bm.is_bounce()) eq_('5.1.1', bm.bounce.status) - ok_(bm.bounce.diagnostic_code) + eq_('smtp; 550-5.1.1 The email account that you tried to reach does' + ' not exist. Please try 550-5.1.1 double-checking the recipient\'s email' + ' address for typos or 550-5.1.1 unnecessary spaces. Learn more at' + ' 550 5.1.1 http://mail.google.com/support/bin/answer.py?answer=6596' + ' 17si20661415yxe.22', + bm.bounce.diagnostic_code) def test_bounce_analyzer_on_regular(): diff --git a/tests/mime/message/fallback/fallback_test.py b/tests/mime/message/fallback/fallback_test.py index 938400b..16b98ce 100644 --- a/tests/mime/message/fallback/fallback_test.py +++ b/tests/mime/message/fallback/fallback_test.py @@ -1,16 +1,18 @@ # coding:utf-8 -from nose.tools import * -from mock import * import email -from flanker.mime.message.fallback import create -from flanker.mime.message import errors -from flanker.mime import recover from cStringIO import StringIO from contextlib import closing from email import message_from_string -from .... import * +from nose.tools import ok_, eq_, assert_false + +from flanker.mime.message.fallback import create +from flanker.mime import recover +from tests import (IPHONE, ENCLOSED, TORTURE, TEXT_ONLY, MAILFORMED_HEADERS, + SPAM_BROKEN_HEADERS, BILINGUAL, MULTI_RECEIVED_HEADERS, + MAILGUN_PIC, BOUNCE) + def bad_string_test(): mime = "Content-Type: multipart/broken\n\n" @@ -94,38 +96,99 @@ def message_content_dispositions_test(): def message_from_python_test(): - message = create.from_python(email.message_from_string(ENCLOSED)) + message = create.from_string(ENCLOSED) eq_(2, len(message.parts)) eq_('multipart/alternative', message.parts[1].enclosed.content_type) eq_('multipart/mixed', message.content_type) assert_false(message.body) message.headers['Sasha'] = 'Hello!' - message.remove_headers("Subject", "Nonexisting") message.parts[1].enclosed.headers['Yo'] = u'Man' ok_(message.to_string()) ok_(str(message)) ok_(str(message.parts[0])) + eq_('4FEEF9B3.7060508@example.net', message.message_id) + eq_('Wow', message.subject) m = message.get_attached_message() eq_('multipart/alternative', str(m.content_type)) - eq_('Thanks!', m.headers['Subject']) + eq_('Thanks!', m.subject) + + +def set_message_id_test(): + # Given + message = create.from_string(ENCLOSED) + + # When + message.message_id = 'some.message.id@example.net' + + # Then + eq_('some.message.id@example.net', message.message_id) + eq_('', message.headers['Message-Id']) + + +def clean_subject_test(): + # Given + message = create.from_string(ENCLOSED) + message.headers['Subject'] = 'FWD: RE: FW: Foo Bar' + + # When/Then + eq_('Foo Bar', message.clean_subject) + + +def references_test(): + # Given + message = create.from_python( + email.message_from_string(MULTI_RECEIVED_HEADERS)) + + # When/Then + eq_({'AANLkTi=1ANR2FzeeQ-vK3-_ty0gUrOsAxMRYkob6CL-c@mail.gmail.com', + 'AANLkTinUdYK2NpEiYCKGnCEp_OXKqst_bWNdBVHsfDVh@mail.gmail.com'}, + set(message.references)) + + +def detected_fields_test(): + # Given + message = create.from_string(MAILGUN_PIC) + attachment = message.parts[1] + + # When/Then + eq_('mailgun.png', attachment.detected_file_name) + eq_('png', attachment.detected_subtype) + eq_('image', attachment.detected_format) + ok_(not attachment.is_body()) + + +def bounce_test(): + # When + message = create.from_string(BOUNCE) + + # Then + ok_(message.is_bounce()) + eq_('5.1.1', message.bounce.status) + eq_('smtp; 550-5.1.1 The email account that you tried to reach does ' + 'not exist. Please try 550-5.1.1 double-checking the recipient\'s email ' + 'address for typos or 550-5.1.1 unnecessary spaces. Learn more at ' + '550 5.1.1 http://mail.google.com/support/bin/answer.py?answer=6596 ' + '17si20661415yxe.22', + message.bounce.diagnostic_code) def torture_test(): message = create.from_string(TORTURE) ok_(list(message.walk(with_self=True))) ok_(message.size) - message.parts[0].content_encoding message.parts[0].content_encoding = 'blablac' + def text_only_test(): message = create.from_string(TEXT_ONLY) eq_(u"Hello,\nI'm just testing message parsing\n\nBR,\nBob", message.body) - eq_(None, message.bounce) + ok_(not message.is_bounce()) eq_(None, message.get_attached_message()) + def message_headers_test(): message = create.from_python(email.message_from_string(ENCLOSED)) diff --git a/tests/mime/message/part_test.py b/tests/mime/message/part_test.py index a870f36..4b7a54b 100644 --- a/tests/mime/message/part_test.py +++ b/tests/mime/message/part_test.py @@ -1,17 +1,21 @@ # coding:utf-8 -import re -from nose.tools import * -from mock import * -from flanker.mime.create import multipart, text -from flanker.mime.message.scanner import scan -from flanker.mime.message.errors import EncodingError, DecodingError from email import message_from_string from contextlib import closing from cStringIO import StringIO -from flanker.mime.message.part import encode_transfer_encoding -from ... import * -from .scanner_test import TORTURE_PARTS, tree_to_string +from nose.tools import eq_, ok_, assert_false, assert_raises, assert_less + +from flanker.mime.create import multipart, text +from flanker.mime.message.scanner import scan +from flanker.mime.message.errors import EncodingError, DecodingError +from flanker.mime.message.part import encode_transfer_encoding +from tests import (BILINGUAL, ENCLOSED, TORTURE, TORTURE_PART, + ENCLOSED_BROKEN_ENCODING, EIGHT_BIT, QUOTED_PRINTABLE, + TEXT_ONLY, ENCLOSED_BROKEN_BODY, RUSSIAN_ATTACH_YAHOO, + MAILGUN_PIC, MAILGUN_PNG, MULTIPART, IPHONE, + SPAM_BROKEN_CTYPE, BOUNCE, NDN, NO_CTYPE, RELATIVE, + MULTI_RECEIVED_HEADERS) +from tests.mime.message.scanner_test import TORTURE_PARTS, tree_to_string def readonly_immutability_test(): @@ -230,6 +234,29 @@ def ascii_to_unicode_test(): eq_(unicode_value, message.body) +def correct_charset_test(): + # Given + message = scan(TEXT_ONLY) + eq_('iso-8859-1', message.charset) + + # When + message.charset = 'utf-8' + + # Then + eq_('utf-8', message.charset) + eq_('utf-8', str(message.headers['Content-Type'].get_charset())) + + +def set_message_id_test(): + # Given + message = scan(MULTI_RECEIVED_HEADERS) + + # When/Then + eq_({'AANLkTi=1ANR2FzeeQ-vK3-_ty0gUrOsAxMRYkob6CL-c@mail.gmail.com', + 'AANLkTinUdYK2NpEiYCKGnCEp_OXKqst_bWNdBVHsfDVh@mail.gmail.com'}, + set(message.references)) + + def ascii_to_quoted_printable_test(): """Make sure that ascii uprades to quoted-printable if it has long lines""" # contains unicode chars -- 2.43.0