Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate a multipart/mime message with correct CRLF in Python?

Tags:

python

mime

I need to generate a multipart/mime message to send as a response to a HTTP request but am hitting either a bug or limitation in the Python email.* package.

The problem is that using Python 2.6, the message.as_string() call below generates a string with \n rather that CRLF as the line endings:

message = MIMEMultipart()
for image in images:
    f = image.open('rb')
    img = MIMEImage(f.read(), _encoder=encode_7or8bit)
    message.attach(img)


message.as_string()

There doesn't seem to be any way to persuade it to use the (MIME standard) CRLF. The Generator class that seems it should be able to do this, doesn't.

What have other people done to get round this?

like image 296
Malcolm Box Avatar asked Jun 21 '10 17:06

Malcolm Box


2 Answers

This was a bug in Python that has now been fixed: http://hg.python.org/lookup/r85811

It should now be possible to use the MIME libraries over non-email transports and have sensible things happen.

like image 148
Malcolm Box Avatar answered Sep 21 '22 17:09

Malcolm Box


What about a simple hack

message.as_string().replace('\n', '\r\n')

? Inelegant, but should work (and a bug report should be entered at the Python tracker).

like image 35
Alex Martelli Avatar answered Sep 22 '22 17:09

Alex Martelli