How to send a zip file as an attachment in python?

后端 未结 2 2042
春和景丽
春和景丽 2020-12-10 14:37

I have looked through many tutorials, as well as other question here on stack overflow, and the documentation and explanation are at minimum, just unexplained code. I would

相关标签:
2条回答
  • 2020-12-10 15:07

    I agree the email package is not well documented yet. I investigated it before and wrote a wrapper module that simplifies these kinds of tasks. For example, the following works:

    from pycopia import ezmail
    
    # Get the data
    data = open("/usr/lib64/python2.7/test/zipdir.zip").read()
    
    # Make a proper mime message object.
    zipattachement = ezmail.MIMEApplication.MIMEApplication(data, "zip",
            filename="zipdir.zip")
    
    # send it.
    ezmail.ezmail(["Here is the zip file.", zipattachement],
            To="me@mydomain.com", From="me@mydomain.com", subject="zip send test")
    

    And that's all you need once you have everything installed and configured. :-)

    0 讨论(0)
  • 2020-12-10 15:10

    I don't really see the problem. Just omit the part which creates the zip file and, instead, just load the zip file you have.

    Essentially, this part here

    msg = MIMEBase('application', 'zip')
    msg.set_payload(zf.read())
    encoders.encode_base64(msg)
    msg.add_header('Content-Disposition', 'attachment', 
                   filename=the_file + '.zip')
    themsg.attach(msg)
    

    creates the attachment. The

    msg.set_payload(zf.read())
    

    sets, well, the payload of the attachment to what you read from the file zf (probably meaning zip file).

    Just open your zip file beforehand and let this line read from it.

    0 讨论(0)
提交回复
热议问题