Question

How can I construct a MIME multipart message in Python? I've tried the email package of Python but it appears broken -- it doesn't properly do binary sections (sets their Content-Transfer-Encoding to base64 and leaves the data as binary). Note it is very important the actual data is binary encoded, and not base64, for my application. I need to minimize the size.

This is the code I tried.

from email import message, mime, generator, encoders
from email.mime import multipart, text, image
from cStringIO import StringIO
import os

m = multipart.MIMEMultipart( "related" )

part = text.MIMEText( "text", "plain" )
part.set_payload( "hello" )
part.add_header( 'Content-Disposition', 'asset', name='abc' )
m.attach( part )

part = image.MIMEImage( "image", "x-other" )
part.set_payload( os.urandom(200) )
m.attach( part )

fp = StringIO()
g = generator.Generator( fp, mangle_from_ = False, maxheaderlen = 1000 )
g.flatten(m)
print( fp.getvalue() )
Was it helpful?

Solution

You can force whichever Content-Transfer-Encoding you want like this:

part = image.MIMEImage( "image", "x-other", encoders.encode_noop )
part.set_payload( os.urandom(200) )
part.add_header( 'Content-Transfer-Encoding', 'binary' )
m.attach( part )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top