Exemple #1
0
def to_message(message):

    text = None
    if message.body:
        text = MIMENonMultipart("text", "plain")
        payload = message.body
        ctenc = message.body_transfer_encoding
        if ctenc:
            payload = encode_string(ctenc, payload)
            text.add_header('Content-Transfer-Encoding', ctnec)
        text.set_payload(payload, message.body_charset)

    html = None
    if message.html:
        html = MIMENonMultipart("text", "html")
        payload = message.html
        ctenc = message.html_transfer_encoding
        if ctenc:
            payload = encode_string(ctenc, payload)
            html.add_header('Content-Transfer-Encoding', ctnec)
        html.set_payload(payload, message.html_charset)

    body = None
    if text and html:
        body = MIMEMultipart("alternative", _subparts=[html, text])
    elif html:
        body = html
    elif text:
        body = text

    mail = None
    if len(message.attachments) > 1 or (body and message.attachments):
        mail = MIMEMultipart("mixed")
        if body:
            mail.attach(body)
        for attachment in message.attachments:
            mail.attach(attachment_to_message(attachment))
    elif not body and message.attachments:
        mail = attachment_to_message(message.attachments[0])
    elif body:
        mail = body
    return mail
Exemple #2
0
def attachment_to_message(attachment):
    mtype, stype = attachment.content_type.split('/')
    if attachment.filename:
        msg = MIMENonMultipart(mtype, stype, name=attachment.filename)
    else:
        msg = MIMENonMultipart(mtype, stype)
    if attachment.disposition:
        if attachment.filename:
            msg.add_header('Content-Dispsition', attachment.disposition,
                    filename=attachment.filename)
        else:
            msg.add_header('Content-Disposition', attachment.disposition)
    payload = attachment.data
    ctenc = attachment.transfer_encoding
    if ctenc:
        payload = encode_string(ctenc, payload)
        msg.add_header('Content-Transfer-Encoding', ctenc)
    msg.set_payload(payload, attachment.charset)
    return msg