Given a MailBase, this will construct a MIME part that is canonicalized for
    use with the Python email API.

def to_message(base):
    """
    Given a MailBase, this will construct a MIME part that is canonicalized for
    use with the Python email API.
    """
    ctype, ctparams = base.get_content_type()

    if not ctype:
        if base.parts:
            ctype = 'multipart/mixed'
        else:
            ctype = 'text/plain'

    maintype, subtype = ctype.split('/')
    is_text = maintype == 'text'
    is_multipart = maintype == 'multipart'

    if base.parts and not is_multipart:
        raise RuntimeError(
            'Content type should be multipart, not %r' % ctype
            )

    body = base.get_body()
    ctenc = base.get_transfer_encoding()
    charset = ctparams.get('charset')

    if is_multipart:
        out = MIMEMultipart(subtype, **ctparams)
    else:
        out = MIMENonMultipart(maintype, subtype, **ctparams)
        if ctenc:
            out['Content-Transfer-Encoding'] = ctenc
        if isinstance(body, text_type):
            if not charset:
                if is_text:
                    charset, _ = best_charset(body)
                else:
                    charset = 'utf-8'
            if PY2:
                body = body.encode(charset)
            else: # pragma: no cover
                body = body.encode(charset, 'surrogateescape')
        if body is not None:
            if ctenc:
                body = transfer_encode(ctenc, body)
            if not PY2: # pragma: no cover
                body = body.decode(charset or 'ascii', 'replace')
        out.set_payload(body, charset) 

    for k in base.keys(): # returned sorted
        value = base[k]
        if not value:
            continue
        out[k] = value

    cdisp, cdisp_params = base.get_content_disposition()

    if cdisp:
        out.add_header('Content-Disposition', cdisp, **cdisp_params)

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

    return out