Re: Generating zipped or gzipped attachment with email package?

Tony Nelson <[email protected]>
Newsgroups gmane.comp.python.mime.devel
Message-ID <p04330101c63b40c86fe9@[192.168.123.162]>
At 11:23 -0500 05/21/2009, [email protected] wrote:
>(I posted this earlier to [email protected] then remembered we have an
>email package sig.  I hope it's ok to ask usage questions here...)
>
>I have a script which allows me to generate MIME messages with appropriate
>attachments.  It's essentially a lightly modified version of the second
>example from this page of the email package docs:
>
>    http://docs.python.org/library/email-examples.html
>
>I want to modify my script to automatically zip or gzip files which exceed
>some size threshold.  Doing the zip/gzip dance is no problem.  I'm concerned
>about how to specify that properly with the email package.  For example,
>consider a large CSV file.  I figure out the MIME type is text/csv.  Now
>suppose I gzip the file before attaching it.  How would this code change to
>specify the compression where "path" is now compressed?
>
>    if maintype == 'text':
>        fp = open(path)
>        # Note: we should handle calculating the charset
>        msg = MIMEText(fp.read(), _subtype=subtype)
>        fp.close()
>
>I guess I'm asking if I can have the Content-Type still be text/csv with
>some other MIME header indicating the file is compressed.  If so, how do I
>achieve that when attaching the compressed file to the message?

I think (untested):

    if maintype == 'text':
        fp = open(path)
        data = fp.read()
        fp.close()
        name = os.basename(path)
        if len(data) > datamax:
        #    do the zip/gzip compression to data
        #    set _subtype to 'zip' or 'x-gzip', or omit for octet-stream
            msg = MIMEApplication( data,
                _subtype='zip',
                _encoder=email.encoders.encode_base64,
                name=name )
        else:
            msg = MIMEText(data)
        del msg['Content-Disposition']   # paranoia
        msg.add_header('Content-Disposition',
            'attachment',   # or 'inline' and omit the name
            filename=name )

This will set the Content-Type: to "application/zip", reflecting the actual
type, encode to Base64 so the payload is ASCII, also setting the
Content-Transfer-Encoding, set a default name, and tell the MUA whether to
try to display the payload or save it as a file (also setting a default
name).
-- 
____________________________________________________________________
TonyN.:'                       <mailto:[email protected]>
      '                              <http://www.georgeanelson.com/>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.