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 """ # fix and sanitize content type string and get main and sub parts: main, sub = fix_content_type( content_type, default=('application', 'octet-stream')) # adjust content type based on body or filename if it's not too accurate content_type = adjust_content_type( ContentType(main, sub), body, filename) if content_type.main == 'message': try: message = message_container(from_string(body)) message.headers['Content-Disposition'] = WithParams(disposition) return message except DecodingError: content_type = ContentType('application', 'octet-stream') return binary( content_type.main, content_type.sub, body, filename, disposition, charset)
def text(subtype, body, charset=None, disposition=None, filename=None): return MimePart(container=Body(content_type=ContentType("text", subtype), body=body, charset=charset, disposition=disposition, filename=filename), is_root=True)
def message_headers_mutation_test(): """ FallbackMimePart headers match MimePart headers exactly for the same input. """ # Given orig = create.from_string(ENCLOSED) eq_('Wow', orig.headers['Subject']) eq_(ContentType('multipart', 'mixed', {'boundary': u'===============6195527458677812340=='}), orig.headers['Content-Type']) # When del orig.headers['Subject'] orig.headers['Content-Type'] = ContentType('text', 'foo') orig.headers.prepend('foo-bar', 'hello') orig.headers.add('blah', 'kitty') restored = create.from_python(orig.to_python_message()) # Then ok_('Subject' not in restored.headers) eq_('', restored.subject) eq_(ContentType('text', 'foo'), restored.headers['Content-Type'])
def binary(maintype, subtype, body, filename=None, disposition=None, charset=None, trust_ctype=False): return MimePart(container=Body(content_type=ContentType(maintype, subtype), trust_ctype=trust_ctype, body=body, charset=charset, disposition=disposition, filename=filename), is_root=True)
def message_container(message): part = MimePart( container=Part(ContentType("message", "rfc822")), enclosed=message) message.set_root(False) return part
def multipart(subtype): return MimePart( container=Part( ContentType( "multipart", subtype, {"boundary": uuid.uuid4().hex})), is_root=True)