<commit_before># The code in this module is entirely lifted from the Lamson project
# (http://lamsonproject.org/).  Its copyright is:

# Copyright (c) 2008, <NAME>
# All rights reserved.

# It is provided under this license:

# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:

# * Redistributions of source code must retain the above copyright notice, this
#   list of conditions and the following disclaimer.

# * Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.

# * Neither the name of the <NAME> nor the names of its contributors may
#   be used to endorse or promote products derived from this software without
#   specific prior written permission.

# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

import cgi
import os
import quopri
import sys
import mimetypes
import string
from email.mime.base import MIMEBase

try:
    from base64 import encodestring as base64_encodestring
    # pyflakes
    base64_encodestring  # pragma: no cover
except ImportError:
    # BBB Python 2 compat
    from base64 import encodestring as base64_encodestring

try:
    text_type = unicode
except NameError:
    text_type = str


from repoze.sendmail import encoding
from .exceptions import InvalidMessage

def normalize_header(header):
    return string.capwords(header.lower(), '-')

def parse_header(header):
    if header:
        return cgi.parse_header(header)
    else:
        return header, {}


class EncodingError(Exception):
    """Thrown when there is an encoding error."""
    pass


class MailBase(object):
    """MailBase is used as the basis of lamson.mail and contains the basics of
    encoding an email.  You actually can do all your email processing with this
    class, but it's more raw.
    """
    def __init__(self, items=()):
        self.headers = dict(items)
        self.parts = []
        self.body = None
        self.content_encoding = {'Content-Type': (None, {}),
                                 'Content-Disposition': (None, {}),
                                 'Content-Transfer-Encoding': None}

    def __getitem__(self, key):
        return self.headers.get(normalize_header(key), None)

    def __len__(self):
        return len(self.headers)

    def __iter__(self):
        return iter(self.headers)

    def __contains__(self, key):
        return normalize_header(key) in self.headers

    def __setitem__(self, key, value):
        self.headers[normalize_header(key)] = value

    def __delitem__(self, key):
        del self.headers[normalize_header(key)]

    def __nonzero__(self):
        return self.body != None or len(
            self.headers) > 0 or len(self.parts) > 0
    __bool__ = __nonzero__

    def keys(self):
        """Returns the sorted keys."""
        return sorted(self.headers.keys())

    def attach_file(self, filename, data, ctype, disposition,
                    transfer_encoding=None):
        """
        A file attachment is a raw attachment with a disposition that
        indicates the file name.
        """
        assert filename, "You can't attach a file without a filename."

        if not isinstance(data, bytes):
            raise InvalidMessage(
                'Attachment data must be bytes if it is not read from '
                'filename: got %r' % data
                )
            
        ctype = ctype.lower()
        part = MailBase()
        part.body = data
        part.content_encoding['Content-Type'] = (ctype, {'name': filename})
        part.content_encoding['Content-Disposition'] = (disposition,
                                                        {'filename': filename})
        part.content_encoding['Content-Transfer-Encoding'] = transfer_encoding
        self.parts.append(part)

    def attach_binary(self, data, ctype):
        """
        This attaches a simple binary part.
        """
        if not isinstance(data, bytes):
            raise InvalidMessage(
                'Attachment data must be bytes; got %r' % data
                )
            
        ctype = ctype.lower()
        part = MailBase()
        part.body = data
        part.content_encoding['Content-Type'] = (ctype, {})
        part.content_encoding['Content-Disposition'] = ('attachment', {})
        part.content_encoding['Content-Transfer-Encoding'] = 'base64'
        self.parts.append(part)
        part = MailBase()

    def attach_text(self, data, ctype):
        """
        This attaches a simple text part.
        """
        ctype = ctype.lower()
        part = MailBase()
        ctype, params = parse_header(ctype)
        body = data
        charset = params.pop('charset', None)
        charset, body = charset_encode_body(charset, data)
        if charset:
            params['charset'] = charset
        part.body = body
        part.content_encoding['Content-Type'] = (ctype, params)
        self.parts.append(part)

    def walk(self):
        for p in self.parts:
            yield p
            for x in p.walk():
                yield x


class MailResponse(object):
    """
    You are given MailResponse objects from the lamson.view methods, and
    whenever you want to generate an email to send to someone.  It has the
    same basic functionality as MailRequest, but it is designed to be written
    to, rather than read from (although you can do both).

    You can easily set a Body or Html during creation or after by passing it
    as __init__ parameters, or by setting those attributes.

    You can initially set the From, To, and Subject, but they are headers so
    use the dict notation to change them: msg['From'] = '<EMAIL>'.

    The message is not fully crafted until right when you convert it with
    MailResponse.to_message.  This lets you change it and work with it, then
    send it out when it's ready.
    """
    def __init__(self, To=None, From=None, Subject=None, Body=None, Html=None):
        self.Body = Body
        self.Html = Html
        self.base = MailBase(
            [('To', To), ('From', From), ('Subject', Subject)])
        self.multipart = self.Body and self.Html
        self.attachments = []

    def __contains__(self, key):
        return self.base.__contains__(key)

    def __getitem__(self, key):
        return self.base.__getitem__(key)

    def __setitem__(self, key, val):
        return self.base.__setitem__(key, val)

    def __delitem__(self, name):
        del self.base[name]

    def attach(self, filename=None, content_type=None, data=None,
               disposition=None, transfer_encoding=None):
        """

        Simplifies attaching files from disk or data as files.  To attach
        simple text simple give data and a content_type.  To attach a file,
        give the data/content_type/filename/disposition/transfer-encoding
        combination.

        For convenience, if you don't give data and only a filename, then it
        will read that file's contents when you call to_message() later.  If
        you give data and filename then it will assume you've filled data
        with what the file's contents are and filename is just the name to
        use.
        """

        assert filename or data, ("You must give a filename or some data to "
                                  "attach.")
        assert data or os.path.exists(filename), ("File doesn't exist, and no "
                                                  "data given.")

        self.multipart = True

        if filename and not content_type:
            content_type, enc = mimetypes.guess_type(filename)

        assert content_type, ("No content type given, and couldn't guess "
                              "from the filename: %r" % filename)

        self.attachments.append({'filename': filename,
                                 'content_type': content_type,
                                 'data': data,
                                 'disposition': disposition,
                                 'transfer_encoding': transfer_encoding})

    def attach_part(self, part):
        """
        Attaches a raw MailBase part from a MailRequest (or anywhere)
        so that you can copy it over.
        """
        self.multipart = True

        self.attachments.append({'filename': None,
                                 'content_type': None,
                                 'data': None,
                                 'disposition': None,
                                 'transfer_encoding': None,
                                 'part': part,
                                 })

    def attach_all_parts(self, mail_request):
        """
        Used for copying the attachment parts of a mail.MailRequest
        object for mailing lists that need to maintain attachments.
        """
        for part in mail_request.all_parts():
            self.attach_part(part)

        self.base.content_encoding = mail_request.base.content_encoding.copy()

    def clear(self):
        """
        Clears out the attachments so you can redo them.  Use this to keep the
        headers for a series of different messages with different attachments.
        """
        del self.attachments[:]
        del self.base.parts[:]
        self.multipart = False

    def update(self, message):
        """
        Used to easily set a bunch of heading from another dict
        like object.
        """
        for k in message.keys():
            self.base[k] = message[k]

    def __str__(self):
        """
        Converts to a string.
        """
        return self.to_message().as_string()

    def _encode_attachment(self, filename=None, content_type=None, data=None,
                           disposition=None, transfer_encoding=None,
                           part=None):
        """
        Used internally to take the attachments mentioned in self.attachments
        and do the actual encoding in a lazy way when you call to_message.
        """
        if part:
            self.base.parts.append(part)
            
        elif filename:
            if not data:
                # should be opened with binary mode to encode the data later
                f = open(filename, mode='rb')
                data = f.read()
                f.close()

            self.base.attach_file(
                filename,
                data,
                content_type,
                disposition or 'attachment',
                transfer_encoding or 'base64'
                )

        else:
            if not isinstance(data, bytes):
                raise InvalidMessage(
                    'Attachment data must be bytes if it is not a file: '
                    'got %s' % data)
            self.base.attach_binary(data, content_type)

        ctype = self.base.content_encoding['Content-Type'][0]

        if ctype and not ctype.startswith('multipart'):
            self.base.content_encoding[
                'Content-Type'] = ('multipart/mixed', {})

    def to_message(self):
        """
        Figures out all the required steps to finally craft the
        message you need and return it.  The resulting message
        is also available as a self.base attribute.

        What is returned is a Python email API message you can
        use with those APIs.  The self.base attribute is the raw
        lamson.encoding.MailBase.
        """
        del self.base.parts[:]

        if isinstance(self.Body, MailBase):
            body_text = self.Body.body
            ct, params = self.Body.content_encoding['Content-Type']
            charset = params.pop('charset', None)
            charset, self.Body.body = charset_encode_body(charset, body_text)
            params['charset'] = charset
            self.Body.content_encoding['Content-Type'] = ('text/plain', params)
            
        if isinstance(self.Html, MailBase):
            html_text = self.Html.body
            ct, params = self.Html.content_encoding['Content-Type']
            charset = params.pop('charset', None)
            charset, self.Html.body = charset_encode_body(charset, html_text)
            params['charset'] = charset
            self.Html.content_encoding['Content-Type'] = ('text/html', params)

        part = self.base
        if self.Body and self.Html:
            self.multipart = True
            if self.attachments:
                part = MailBase()
                self.base.parts.append(part)
            part.content_encoding['Content-Type'] = (
                'multipart/alternative', {})

        if self.multipart:
            self.base.body = None
            if isinstance(self.Body, MailBase):
                part.parts.append(self.Body)
            elif self.Body:
                part.attach_text(self.Body, 'text/plain')

            # Per RFC2046, HTML part is last in multipart/alternative
            if isinstance(self.Html, MailBase):
                part.parts.append(self.Html)
            elif self.Html:
                part.attach_text(self.Html, 'text/html')

            for args in self.attachments:
                self._encode_attachment(**args)

        elif self.Body:
            if isinstance(self.Body, MailBase):
                self.base.body = self.Body.body
                self.base.content_encoding.update(**self.Body.content_encoding)
            else:
                params = {}
                charset, self.base.body = charset_encode_body(None, self.Body)
                if charset:
                    params['charset'] = charset
                self.base.content_encoding['Content-Type'] = (
                    'text/plain', params)

        elif self.Html:
            if isinstance(self.Html, MailBase):
                self.base.body = self.Html.body
                self.base.content_encoding.update(**self.Html.content_encoding)
            else:
                params = {}
                charset, self.base.body = charset_encode_body(None, self.Html)
                if charset:
                    params['charset'] = charset
                self.base.content_encoding['Content-Type'] = (
                    'text/html', params)

        return to_message(self.base)

    def all_parts(self):
        """
        Returns all the encoded parts.  Only useful for debugging
        or inspecting after calling to_message().
        """
        return self.base.parts

    def keys(self):
        return self.base.keys()


def to_message(mail):
    """
    Given a MailBase message, this will construct a MIMEPart
    that is canonicalized for use with the Python email API.
    """
    ctype, params = mail.content_encoding['Content-Type']

    if not ctype:
        if mail.parts:
            ctype = 'multipart/mixed'
        else:
            ctype = 'text/plain'
    else:
        if mail.parts:
            assert ctype.startswith(("multipart", "message")), (
                "Content type should be multipart or message, not %r" % ctype)

    # adjust the content type according to what it should be now
    mail.content_encoding['Content-Type'] = (ctype, params)

    try:
        out = MIMEPart(ctype, **params)
    except TypeError as exc:  # pragma: no cover
        raise EncodingError("Content-Type malformed, not allowed: %r; "
                            "%r (Python ERROR: %s" %
                            (ctype, params, exc.message))

    for k in mail.keys():
        value = mail[k]
        if k.lower() in encoding.ADDR_HEADERS:
            if is_nonstr_iter(value):  # not a string
                value = ", ".join(value)
        if value == '':
            continue
        out[k] = value

    out.extract_payload(mail)

    # go through the children
    for part in mail.parts:
        out.attach(to_message(part))

    return out


class MIMEPart(MIMEBase):
    """
    A reimplementation of nearly everything in email.mime to be more useful
    for actually attaching things.  Rather than one class for every type of
    thing you'd encode, there's just this one, and it figures out how to
    encode what you ask it.
    """
    def __init__(self, type, **params):
        self.maintype, self.subtype = type.split('/')
        MIMEBase.__init__(self, self.maintype, self.subtype, **params)

    def extract_payload(self, mail):
        if mail.body is None:
            return

        body = mail.body

        ctype, ctype_params = mail.content_encoding['Content-Type']
        cdisp, cdisp_params = mail.content_encoding['Content-Disposition']
        ctenc = mail.content_encoding.get('Content-Transfer-Encoding')

        assert ctype, ("Extract payload requires that mail.content_encoding "
                       "have a valid Content-Type.")

        charset = ctype_params.get('charset')

        if cdisp:
            # replicate the content-disposition settings
            self.add_header('Content-Disposition', cdisp, **cdisp_params)
        if ctenc:
            # need to encode because repoze.sendmail don't handle attachments
            body = transfer_encode_string(ctenc, body, charset)
            self.add_header('Content-Transfer-Encoding', ctenc)

        self.set_payload(body, charset=charset)

    def __repr__(self):
        return "<MIMEPart '%s/%s': '%s', %r, multipart=%r>" % (
            self.subtype,
            self.maintype,
            self['Content-Type'],
            self['Content-Disposition'],
            self.is_multipart())


if sys.version < '3':
    def charset_encode_body(charset, data):
        # on python 2, must return bytes
        if isinstance(data, bytes):
            # - data is bytes and there's a charset
            #   trust that body and charset match and do nothing
            if charset:
                return charset, data
            else:
                # - data is bytes and there's no charset
                #   try to decode body from ascii and raise an exception if cant
                try:
                    data.decode('ascii')
                except UnicodeError:
                    raise InvalidMessage(
                        'Body is bytes, but no charset supplied and '
                        'cannot decode body from ascii'
                        )
                return None, data
        else:
            if charset:
                # - data is text and there's a charset
                #   trust that body can be encoded using charset and encode it
                return charset, data.encode(charset)
            else:
                # - data is text and there's no charset
                #   use best_charset
                best_charset, encoded = encoding.best_charset(data)
                if best_charset == 'ascii':
                    best_charset = None
                return best_charset, encoded
else:
    def charset_encode_body(charset, data):
        # on python 3, must return text
        if isinstance(data, bytes):
            # - data is bytes and there's a charset
            #   trust that body and charset match and do nothing
            if charset:
                return charset, data.decode(charset)
            else:
                # - data is bytes and there's no charset
                #   try to decode body from ascii and raise an exception if cant
                try:
                    return None, data.decode('ascii')
                except UnicodeError:
                    raise InvalidMessage(
                        'Body is bytes, but no charset supplied and '
                        'cannot decode body from ascii'
                        )
        else:
            if charset:
                # - data is text and there's a charset
                #   trust that body can be encoded using charset and encode it
                return charset, data
            else:
                # - data is text and there's no charset
                #   use best_charset
                best_charset, encoded = encoding.best_charset(data)
                if best_charset == 'ascii':
                    best_charset = None
                return best_charset, data
                    
def transfer_encode_string(encoding, data, charset):
    encoded = data
    if isinstance(data, text_type):
        if charset is None:
            charset = 'ascii'
        data = data.encode(charset)
    if encoding == 'base64':
        encoded = base64_encodestring(data).decode('ascii')
    elif encoding == 'quoted-printable':
        encoded = quopri.encodestring(data).decode('ascii')
    return encoded

# BBB Python 2 vs 3 compat
if sys.version < '3':
    def is_nonstr_iter(v):
        return hasattr(v, '__iter__')
else:
    def is_nonstr_iter(v):  # pragma: no cover
        if isinstance(v, str):
            return False
        return hasattr(v, '__iter__')

    
<commit_msg>accept other spellings for quopri, raise an exception for an unknown encoding<commit_after># The code in this module is entirely lifted from the Lamson project
# (http://lamsonproject.org/).  Its copyright is:

# Copyright (c) 2008, <NAME>
# All rights reserved.

# It is provided under this license:

# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:

# * Redistributions of source code must retain the above copyright notice, this
#   list of conditions and the following disclaimer.

# * Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.

# * Neither the name of the Zed A. Shaw nor the names of its contributors may
#   be used to endorse or promote products derived from this software without
#   specific prior written permission.

# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

import cgi
import os
import quopri
import sys
import mimetypes
import string
from email.mime.base import MIMEBase

try:
    from base64 import encodestring as base64_encodestring
    # pyflakes
    base64_encodestring  # pragma: no cover
except ImportError:
    # BBB Python 2 compat
    from base64 import encodestring as base64_encodestring

try:
    text_type = unicode
except NameError:
    text_type = str


from repoze.sendmail import encoding
from .exceptions import InvalidMessage

def normalize_header(header):
    return string.capwords(header.lower(), '-')

def parse_header(header):
    if header:
        return cgi.parse_header(header)
    else:
        return header, {}


class EncodingError(Exception):
    """Thrown when there is an encoding error."""
    pass


class MailBase(object):
    """MailBase is used as the basis of lamson.mail and contains the basics of
    encoding an email.  You actually can do all your email processing with this
    class, but it's more raw.
    """
    def __init__(self, items=()):
        self.headers = dict(items)
        self.parts = []
        self.body = None
        self.content_encoding = {'Content-Type': (None, {}),
                                 'Content-Disposition': (None, {}),
                                 'Content-Transfer-Encoding': None}

    def __getitem__(self, key):
        return self.headers.get(normalize_header(key), None)

    def __len__(self):
        return len(self.headers)

    def __iter__(self):
        return iter(self.headers)

    def __contains__(self, key):
        return normalize_header(key) in self.headers

    def __setitem__(self, key, value):
        self.headers[normalize_header(key)] = value

    def __delitem__(self, key):
        del self.headers[normalize_header(key)]

    def __nonzero__(self):
        return self.body != None or len(
            self.headers) > 0 or len(self.parts) > 0
    __bool__ = __nonzero__

    def keys(self):
        """Returns the sorted keys."""
        return sorted(self.headers.keys())

    def attach_file(self, filename, data, ctype, disposition,
                    transfer_encoding=None):
        """
        A file attachment is a raw attachment with a disposition that
        indicates the file name.
        """
        assert filename, "You can't attach a file without a filename."

        if not isinstance(data, bytes):
            raise InvalidMessage(
                'Attachment data must be bytes if it is not read from '
                'filename: got %r' % data
                )
            
        ctype = ctype.lower()
        part = MailBase()
        part.body = data
        part.content_encoding['Content-Type'] = (ctype, {'name': filename})
        part.content_encoding['Content-Disposition'] = (disposition,
                                                        {'filename': filename})
        part.content_encoding['Content-Transfer-Encoding'] = transfer_encoding
        self.parts.append(part)

    def attach_binary(self, data, ctype):
        """
        This attaches a simple binary part.
        """
        if not isinstance(data, bytes):
            raise InvalidMessage(
                'Attachment data must be bytes; got %r' % data
                )
            
        ctype = ctype.lower()
        part = MailBase()
        part.body = data
        part.content_encoding['Content-Type'] = (ctype, {})
        part.content_encoding['Content-Disposition'] = ('attachment', {})
        part.content_encoding['Content-Transfer-Encoding'] = 'base64'
        self.parts.append(part)
        part = MailBase()

    def attach_text(self, data, ctype):
        """
        This attaches a simple text part.
        """
        ctype = ctype.lower()
        part = MailBase()
        ctype, params = parse_header(ctype)
        body = data
        charset = params.pop('charset', None)
        charset, body = charset_encode_body(charset, data)
        if charset:
            params['charset'] = charset
        part.body = body
        part.content_encoding['Content-Type'] = (ctype, params)
        self.parts.append(part)

    def walk(self):
        for p in self.parts:
            yield p
            for x in p.walk():
                yield x


class MailResponse(object):
    """
    You are given MailResponse objects from the lamson.view methods, and
    whenever you want to generate an email to send to someone.  It has the
    same basic functionality as MailRequest, but it is designed to be written
    to, rather than read from (although you can do both).

    You can easily set a Body or Html during creation or after by passing it
    as __init__ parameters, or by setting those attributes.

    You can initially set the From, To, and Subject, but they are headers so
    use the dict notation to change them: msg['From'] = '<EMAIL>'.

    The message is not fully crafted until right when you convert it with
    MailResponse.to_message.  This lets you change it and work with it, then
    send it out when it's ready.
    """
    def __init__(self, To=None, From=None, Subject=None, Body=None, Html=None):
        self.Body = Body
        self.Html = Html
        self.base = MailBase(
            [('To', To), ('From', From), ('Subject', Subject)])
        self.multipart = self.Body and self.Html
        self.attachments = []

    def __contains__(self, key):
        return self.base.__contains__(key)

    def __getitem__(self, key):
        return self.base.__getitem__(key)

    def __setitem__(self, key, val):
        return self.base.__setitem__(key, val)

    def __delitem__(self, name):
        del self.base[name]

    def attach(self, filename=None, content_type=None, data=None,
               disposition=None, transfer_encoding=None):
        """

        Simplifies attaching files from disk or data as files.  To attach
        simple text simple give data and a content_type.  To attach a file,
        give the data/content_type/filename/disposition/transfer-encoding
        combination.

        For convenience, if you don't give data and only a filename, then it
        will read that file's contents when you call to_message() later.  If
        you give data and filename then it will assume you've filled data
        with what the file's contents are and filename is just the name to
        use.
        """

        assert filename or data, ("You must give a filename or some data to "
                                  "attach.")
        assert data or os.path.exists(filename), ("File doesn't exist, and no "
                                                  "data given.")

        self.multipart = True

        if filename and not content_type:
            content_type, enc = mimetypes.guess_type(filename)

        assert content_type, ("No content type given, and couldn't guess "
                              "from the filename: %r" % filename)

        self.attachments.append({'filename': filename,
                                 'content_type': content_type,
                                 'data': data,
                                 'disposition': disposition,
                                 'transfer_encoding': transfer_encoding})

    def attach_part(self, part):
        """
        Attaches a raw MailBase part from a MailRequest (or anywhere)
        so that you can copy it over.
        """
        self.multipart = True

        self.attachments.append({'filename': None,
                                 'content_type': None,
                                 'data': None,
                                 'disposition': None,
                                 'transfer_encoding': None,
                                 'part': part,
                                 })

    def attach_all_parts(self, mail_request):
        """
        Used for copying the attachment parts of a mail.MailRequest
        object for mailing lists that need to maintain attachments.
        """
        for part in mail_request.all_parts():
            self.attach_part(part)

        self.base.content_encoding = mail_request.base.content_encoding.copy()

    def clear(self):
        """
        Clears out the attachments so you can redo them.  Use this to keep the
        headers for a series of different messages with different attachments.
        """
        del self.attachments[:]
        del self.base.parts[:]
        self.multipart = False

    def update(self, message):
        """
        Used to easily set a bunch of heading from another dict
        like object.
        """
        for k in message.keys():
            self.base[k] = message[k]

    def __str__(self):
        """
        Converts to a string.
        """
        return self.to_message().as_string()

    def _encode_attachment(self, filename=None, content_type=None, data=None,
                           disposition=None, transfer_encoding=None,
                           part=None):
        """
        Used internally to take the attachments mentioned in self.attachments
        and do the actual encoding in a lazy way when you call to_message.
        """
        if part:
            self.base.parts.append(part)
            
        elif filename:
            if not data:
                # should be opened with binary mode to encode the data later
                f = open(filename, mode='rb')
                data = f.read()
                f.close()

            self.base.attach_file(
                filename,
                data,
                content_type,
                disposition or 'attachment',
                transfer_encoding or 'base64'
                )

        else:
            if not isinstance(data, bytes):
                raise InvalidMessage(
                    'Attachment data must be bytes if it is not a file: '
                    'got %s' % data)
            self.base.attach_binary(data, content_type)

        ctype = self.base.content_encoding['Content-Type'][0]

        if ctype and not ctype.startswith('multipart'):
            self.base.content_encoding[
                'Content-Type'] = ('multipart/mixed', {})

    def to_message(self):
        """
        Figures out all the required steps to finally craft the
        message you need and return it.  The resulting message
        is also available as a self.base attribute.

        What is returned is a Python email API message you can
        use with those APIs.  The self.base attribute is the raw
        lamson.encoding.MailBase.
        """
        del self.base.parts[:]

        if isinstance(self.Body, MailBase):
            body_text = self.Body.body
            ct, params = self.Body.content_encoding['Content-Type']
            charset = params.pop('charset', None)
            charset, self.Body.body = charset_encode_body(charset, body_text)
            params['charset'] = charset
            self.Body.content_encoding['Content-Type'] = ('text/plain', params)
            
        if isinstance(self.Html, MailBase):
            html_text = self.Html.body
            ct, params = self.Html.content_encoding['Content-Type']
            charset = params.pop('charset', None)
            charset, self.Html.body = charset_encode_body(charset, html_text)
            params['charset'] = charset
            self.Html.content_encoding['Content-Type'] = ('text/html', params)

        part = self.base
        if self.Body and self.Html:
            self.multipart = True
            if self.attachments:
                part = MailBase()
                self.base.parts.append(part)
            part.content_encoding['Content-Type'] = (
                'multipart/alternative', {})

        if self.multipart:
            self.base.body = None
            if isinstance(self.Body, MailBase):
                part.parts.append(self.Body)
            elif self.Body:
                part.attach_text(self.Body, 'text/plain')

            # Per RFC2046, HTML part is last in multipart/alternative
            if isinstance(self.Html, MailBase):
                part.parts.append(self.Html)
            elif self.Html:
                part.attach_text(self.Html, 'text/html')

            for args in self.attachments:
                self._encode_attachment(**args)

        elif self.Body:
            if isinstance(self.Body, MailBase):
                self.base.body = self.Body.body
                self.base.content_encoding.update(**self.Body.content_encoding)
            else:
                params = {}
                charset, self.base.body = charset_encode_body(None, self.Body)
                if charset:
                    params['charset'] = charset
                self.base.content_encoding['Content-Type'] = (
                    'text/plain', params)

        elif self.Html:
            if isinstance(self.Html, MailBase):
                self.base.body = self.Html.body
                self.base.content_encoding.update(**self.Html.content_encoding)
            else:
                params = {}
                charset, self.base.body = charset_encode_body(None, self.Html)
                if charset:
                    params['charset'] = charset
                self.base.content_encoding['Content-Type'] = (
                    'text/html', params)

        return to_message(self.base)

    def all_parts(self):
        """
        Returns all the encoded parts.  Only useful for debugging
        or inspecting after calling to_message().
        """
        return self.base.parts

    def keys(self):
        return self.base.keys()


def to_message(mail):
    """
    Given a MailBase message, this will construct a MIMEPart
    that is canonicalized for use with the Python email API.
    """
    ctype, params = mail.content_encoding['Content-Type']

    if not ctype:
        if mail.parts:
            ctype = 'multipart/mixed'
        else:
            ctype = 'text/plain'
    else:
        if mail.parts:
            assert ctype.startswith(("multipart", "message")), (
                "Content type should be multipart or message, not %r" % ctype)

    # adjust the content type according to what it should be now
    mail.content_encoding['Content-Type'] = (ctype, params)

    try:
        out = MIMEPart(ctype, **params)
    except TypeError as exc:  # pragma: no cover
        raise EncodingError("Content-Type malformed, not allowed: %r; "
                            "%r (Python ERROR: %s" %
                            (ctype, params, exc.message))

    for k in mail.keys():
        value = mail[k]
        if k.lower() in encoding.ADDR_HEADERS:
            if is_nonstr_iter(value):  # not a string
                value = ", ".join(value)
        if value == '':
            continue
        out[k] = value

    out.extract_payload(mail)

    # go through the children
    for part in mail.parts:
        out.attach(to_message(part))

    return out


class MIMEPart(MIMEBase):
    """
    A reimplementation of nearly everything in email.mime to be more useful
    for actually attaching things.  Rather than one class for every type of
    thing you'd encode, there's just this one, and it figures out how to
    encode what you ask it.
    """
    def __init__(self, type, **params):
        self.maintype, self.subtype = type.split('/')
        MIMEBase.__init__(self, self.maintype, self.subtype, **params)

    def extract_payload(self, mail):
        if mail.body is None:
            return

        body = mail.body

        ctype, ctype_params = mail.content_encoding['Content-Type']
        cdisp, cdisp_params = mail.content_encoding['Content-Disposition']
        ctenc = mail.content_encoding.get('Content-Transfer-Encoding')

        assert ctype, ("Extract payload requires that mail.content_encoding "
                       "have a valid Content-Type.")

        charset = ctype_params.get('charset')

        if cdisp:
            # replicate the content-disposition settings
            self.add_header('Content-Disposition', cdisp, **cdisp_params)
        if ctenc:
            # need to encode because repoze.sendmail don't handle attachments
            body = transfer_encode_string(ctenc, body, charset)
            self.add_header('Content-Transfer-Encoding', ctenc)

        self.set_payload(body, charset=charset)

    def __repr__(self):
        return "<MIMEPart '%s/%s': '%s', %r, multipart=%r>" % (
            self.subtype,
            self.maintype,
            self['Content-Type'],
            self['Content-Disposition'],
            self.is_multipart())


if sys.version < '3':
    def charset_encode_body(charset, data):
        # on python 2, must return bytes
        if isinstance(data, bytes):
            # - data is bytes and there's a charset
            #   trust that body and charset match and do nothing
            if charset:
                return charset, data
            else:
                # - data is bytes and there's no charset
                #   try to decode body from ascii and raise an exception if cant
                try:
                    data.decode('ascii')
                except UnicodeError:
                    raise InvalidMessage(
                        'Body is bytes, but no charset supplied and '
                        'cannot decode body from ascii'
                        )
                return None, data
        else:
            if charset:
                # - data is text and there's a charset
                #   trust that body can be encoded using charset and encode it
                return charset, data.encode(charset)
            else:
                # - data is text and there's no charset
                #   use best_charset
                best_charset, encoded = encoding.best_charset(data)
                if best_charset == 'ascii':
                    best_charset = None
                return best_charset, encoded
else:
    def charset_encode_body(charset, data):
        # on python 3, must return text
        if isinstance(data, bytes):
            # - data is bytes and there's a charset
            #   trust that body and charset match and do nothing
            if charset:
                return charset, data.decode(charset)
            else:
                # - data is bytes and there's no charset
                #   try to decode body from ascii and raise an exception if cant
                try:
                    return None, data.decode('ascii')
                except UnicodeError:
                    raise InvalidMessage(
                        'Body is bytes, but no charset supplied and '
                        'cannot decode body from ascii'
                        )
        else:
            if charset:
                # - data is text and there's a charset
                #   trust that body can be encoded using charset and encode it
                return charset, data
            else:
                # - data is text and there's no charset
                #   use best_charset
                best_charset, encoded = encoding.best_charset(data)
                if best_charset == 'ascii':
                    best_charset = None
                return best_charset, data
                    
def transfer_encode_string(encoding, data, charset):
    encoded = data
    if isinstance(data, text_type):
        if charset is None:
            charset = 'ascii'
        data = data.encode(charset)
    if encoding == 'base64':
        encoded = base64_encodestring(data).decode('ascii')
    elif encoding in ('quoted-printable', 'quoted/printable', 'quopri'):
        encoded = quopri.encodestring(data).decode('ascii')
    elif encoding:
        raise RuntimeError('Unknown transfer encoding %s' % encoding)
    return encoded

# BBB Python 2 vs 3 compat
if sys.version < '3':
    def is_nonstr_iter(v):
        return hasattr(v, '__iter__')
else:
    def is_nonstr_iter(v):  # pragma: no cover
        if isinstance(v, str):
            return False
        return hasattr(v, '__iter__')

    

{'fraction_non_alphanumeric': 0.08430286241920591, 'fraction_numerical': 0.0016620498614958448, 'mean_word_length': 1.8748423916650077, 'pattern_counts': {'":': 0, '<': 14, '<?xml version=': 0, '>': 14, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 32, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7360763', 'n_tokens_mistral': 11594, 'n_tokens_neox': 10821, 'n_words': 3766}