How to convert GIF file(s) to MIME to be mail?

Michael P. Reilly arcege at shore.net
Fri Apr 21 14:31:17 CEST 2000


Paul Martinolich <martinol at nrlssc.navy.mil> wrote:
: I need to run a shell script that will convert a single or multiple
: GIF files into something I can mail to another user.

: How can python do it?

Yup, pretty easily too.  There are some nice standard modules to help
you with this.  I do it by hand often enough.

>>> import MimeWriter, base64
>>> infile = open('/tmp/world.gif', 'rb')
>>> outfile = open('/tmp/world.gif.b64', 'w')
>>> base64.encode(infile, outfile)
>>> outfile.close()
>>> infile.close()
>>> imagesize = os.path.getsize('/tmp/world.gif.b64')
>>> outmime = open('/tmp/outmail.txt', 'w')
>>> mw = MimeWriter.MimeWriter(outmime)
>>> mw.addheader('content-length', imagesize)
>>> f = mw.startbody('image/gif', [('name', 'world.gif')])
>>> outfile = open('/tmp/world.gif.b64', 'r')
>>> f.write(outfile.read())
>>> outmime.close()
>>>

Myself, I always thought the MimeWriter module was overly complicated
(especially linking it with the mimetools module) and I wrote another
module for my own uses called mimecntl.

>>> import mimecntl
>>> imagefname = '/tmp/world.gif'
>>> imagedata = open(imagefname, 'rb')
>>> md = mimecntl.MIME_recoder(image, ctype='image/jpeg')
>>> encoded = md.encode('base64')
>>> encoded['content-length'] = len(encoded) # encoded data size
>>> outmime = open('/tmp/outmail.txt', 'w')
>>> outmime.write( str(encoded) )
>>> outmime.close()
>>>

Making multipart MIME messages instead is as easy as making a list of
them:
>>> second_encoded = mimecntl.MIME_recoder(
...   image2, ctype='image/jpeg').encode('base64')
>>> second_encoded['content-length'] = len(second_encoded)
>>> msg = mimecntl.MIME_document( [encoded, second_encoded] )
>>> outmime = open('/tmp/outmime.txt', 'w')
>>> outmime.write( str(msg) )
>>> outmime.close()

You can find the mimecntl module at
<URL: http://www.shore.net/~arcege/python/mimecntl.py>.

  -Arcege




More information about the Python-list mailing list