Erle Robotics Python Networking Gitbook Free

Composing Nested Multiparts

Now that you know how to generate a message with alternatives and one with attachments, you may be wondering how to do both. To do that, you create a standard multipart for the main message. Then you create a multipart/alternative inside that for your body text, and attach your message formats to it. Finally, you attach the various files. Take a look at for the complete solution.

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import utils, encoders
import mimetypes, sys

def genpart(data, contenttype):
    maintype, subtype = contenttype.split('/')
    if maintype == 'text':
        retval = MIMEText(data, _subtype=subtype)
        retval = MIMEBase(maintype, subtype)
    return retval

def attachment(filename):
    fd = open(filename, 'rb')
    mimetype, mimeencoding = mimetypes.guess_type(filename)
    if mimeencoding or (mimetype is None):
        mimetype = 'application/octet-stream'
    retval = genpart(, mimetype)
    retval.add_header('Content-Disposition', 'attachment',
            filename = filename)
    return retval

messagetext = """Hello,

This is a *great* test message from Chapter 12.  I hope you enjoy it!

-- Anonymous"""
messagehtml = """Hello,<P>
This is a <B>great</B> test message <P>
-- <I>Anonymous</I>"""

msg = MIMEMultipart()
msg['To'] = '[email protected]'
msg['From'] = 'Test Sender <[email protected]>'
msg['Subject'] = 'Test Message'
msg['Date'] = utils.formatdate(localtime = 1)
msg['Message-ID'] = utils.make_msgid()

body = MIMEMultipart('alternative')
body.attach(genpart(messagetext, 'text/plain'))
body.attach(genpart(messagehtml, 'text/html'))

for filename in sys.argv[1:]:
print msg.as_string()