# Path: modoboa_webmail/lib/rfc6266.py
# def build_header(
#     filename, disposition='attachment', filename_compat=None
# ):
#     """Generate a Content-Disposition header for a given filename.
#     For legacy clients that don't understand the filename* parameter,
#     a filename_compat value may be given.
#     It should either be ascii-only (recommended) or iso-8859-1 only.
#     In the later case it should be a character string
#     (unicode in Python 2).
#     Options for generating filename_compat (only useful for legacy clients):
#     - ignore (will only send filename*);
#     - strip accents using unicode's decomposing normalisations,
#     which can be done from unicode data (stdlib), and keep only ascii;
#     - use the ascii transliteration tables from Unidecode (PyPI);
#     - use iso-8859-1
#     Ignore is the safest, and can be used to trigger a fallback
#     to the document location (which can be percent-encoded utf-8
#     if you control the URLs).
#     See https://tools.ietf.org/html/rfc6266#appendix-D
#     """
# 
#     # While this method exists, it could also sanitize the filename
#     # by rejecting slashes or other weirdness that might upset a receiver.
# 
#     if disposition != 'attachment':
#         assert is_token(disposition)
# 
#     rv = disposition
# 
#     if is_token(filename):
#         rv += '; filename=%s' % (filename, )
#         return rv
#     elif is_ascii(filename) and is_lws_safe(filename):
#         qd_filename = qd_quote(filename)
#         rv += '; filename="%s"' % (qd_filename, )
#         if qd_filename == filename:
#             # RFC 6266 claims some implementations are iffy on qdtext's
#             # backslash-escaping, we'll include filename* in that case.
#             return rv
#     elif filename_compat:
#         if is_token(filename_compat):
#             rv += '; filename=%s' % (filename_compat, )
#         else:
#             assert is_lws_safe(filename_compat)
#             rv += '; filename="%s"' % (qd_quote(filename_compat), )
# 
#     # alnum are already considered always-safe, but the rest isn't.
#     # Python encodes ~ when it shouldn't, for example.
#     rv += "; filename*=utf-8''%s" % (percent_encode(
#         filename, safe=attr_chars_nonalnum, encoding='utf-8'), )
# 
#     # This will only encode filename_compat, if it used non-ascii iso-8859-1.
#     return rv.encode('iso-8859-1')


from email import encoders
from email.mime.base import MIMEBase
from django.conf import settings
from django.core.files.uploadhandler import FileUploadHandler, SkipFile
from django.utils.encoding import smart_bytes
from modoboa.lib.exceptions import InternalError
from modoboa.lib.web_utils import size2integer
from modoboa.parameters import tools as param_tools
from .rfc6266 import build_header
    from tempfile import NamedTemporaryFile
import os
import uuid
import six
        try:
            os.remove(fullpath)
        except OSError:
            pass


def create_mail_attachment(attdef, payload=None):
    """Create the MIME part corresponding to the given attachment.

    Mandatory keys: 'fname', 'tmpname', 'content-type'

    :param attdef: a dictionary containing the attachment definition
    :return: a MIMEBase object
    """
    if "content-type" in attdef:
        maintype, subtype = attdef["content-type"].split("/")
    elif "Content-Type" in attdef:
        maintype, subtype = attdef["Content-Type"].split("/")
    else:
        return None
    res = MIMEBase(maintype, subtype)
    if payload is None:
        path = get_storage_path(attdef["tmpname"])
        with open(path, "rb") as fp:
            res.set_payload(fp.read())
    else:
        res.set_payload(payload)
    encoders.encode_base64(res)
    if isinstance(attdef["fname"], six.binary_type):
        attdef["fname"] = attdef["fname"].decode("utf-8")

# Path: modoboa_webmail/lib/rfc6266.py
# def build_header(
#     filename, disposition='attachment', filename_compat=None
# ):
#     """Generate a Content-Disposition header for a given filename.
#     For legacy clients that don't understand the filename* parameter,
#     a filename_compat value may be given.
#     It should either be ascii-only (recommended) or iso-8859-1 only.
#     In the later case it should be a character string
#     (unicode in Python 2).
#     Options for generating filename_compat (only useful for legacy clients):
#     - ignore (will only send filename*);
#     - strip accents using unicode's decomposing normalisations,
#     which can be done from unicode data (stdlib), and keep only ascii;
#     - use the ascii transliteration tables from Unidecode (PyPI);
#     - use iso-8859-1
#     Ignore is the safest, and can be used to trigger a fallback
#     to the document location (which can be percent-encoded utf-8
#     if you control the URLs).
#     See https://tools.ietf.org/html/rfc6266#appendix-D
#     """
# 
#     # While this method exists, it could also sanitize the filename
#     # by rejecting slashes or other weirdness that might upset a receiver.
# 
#     if disposition != 'attachment':
#         assert is_token(disposition)
# 
#     rv = disposition
# 
#     if is_token(filename):
#         rv += '; filename=%s' % (filename, )
#         return rv
#     elif is_ascii(filename) and is_lws_safe(filename):
#         qd_filename = qd_quote(filename)
#         rv += '; filename="%s"' % (qd_filename, )
#         if qd_filename == filename:
#             # RFC 6266 claims some implementations are iffy on qdtext's
#             # backslash-escaping, we'll include filename* in that case.
#             return rv
#     elif filename_compat:
#         if is_token(filename_compat):
#             rv += '; filename=%s' % (filename_compat, )
#         else:
#             assert is_lws_safe(filename_compat)
#             rv += '; filename="%s"' % (qd_quote(filename_compat), )
# 
#     # alnum are already considered always-safe, but the rest isn't.
#     # Python encodes ~ when it shouldn't, for example.
#     rv += "; filename*=utf-8''%s" % (percent_encode(
#         filename, safe=attr_chars_nonalnum, encoding='utf-8'), )
# 
#     # This will only encode filename_compat, if it used non-ascii iso-8859-1.
#     return rv.encode('iso-8859-1')


# Path: modoboa_webmail/lib/attachments.py
from email import encoders
from email.mime.base import MIMEBase
from django.conf import settings
from django.core.files.uploadhandler import FileUploadHandler, SkipFile
from django.utils.encoding import smart_bytes
from modoboa.lib.exceptions import InternalError
from modoboa.lib.web_utils import size2integer
from modoboa.parameters import tools as param_tools
from .rfc6266 import build_header
    from tempfile import NamedTemporaryFile
import os
import uuid
import six

        try:
            os.remove(fullpath)
        except OSError:
            pass


def create_mail_attachment(attdef, payload=None):
    """Create the MIME part corresponding to the given attachment.

    Mandatory keys: 'fname', 'tmpname', 'content-type'

    :param attdef: a dictionary containing the attachment definition
    :return: a MIMEBase object
    """
    if "content-type" in attdef:
        maintype, subtype = attdef["content-type"].split("/")
    elif "Content-Type" in attdef:
        maintype, subtype = attdef["Content-Type"].split("/")
    else:
        return None
    res = MIMEBase(maintype, subtype)
    if payload is None:
        path = get_storage_path(attdef["tmpname"])
        with open(path, "rb") as fp:
            res.set_payload(fp.read())
    else:
        res.set_payload(payload)
    encoders.encode_base64(res)
    if isinstance(attdef["fname"], six.binary_type):
        attdef["fname"] = attdef["fname"].decode("utf-8")

    content_disposition = build_header(attdef["fname"])