How to send a zip file as an attachment in python?
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.
Andy
Love programming. Focused mainly on Android and Ruby on Rails full stack development. I also dabbles in the PHPs. SOreadytohelp
Updated on August 10, 2021Comments
-
Andy almost 3 years
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 like to send a file that I already have zipped, and send it as an attachment. I have tried copy and pasting the code provided, but its not working, hence I cannot fix the problem.
So what I am asking is if anyone knows who to explain how smtplib as well as email and MIME libraries work together to send a file, more specifically, how to do it with a zip file. Any help would be appreciated.
This is the code that everyone refers to:
import smtplib import zipfile import tempfile from email import encoders from email.message import Message from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart def send_file_zipped(the_file, recipients, sender='[email protected]'): myzip = zipfile.ZipFile('file.zip', 'w') # Create the message themsg = MIMEMultipart() themsg['Subject'] = 'File %s' % the_file themsg['To'] = ', '.join(recipients) themsg['From'] = sender themsg.preamble = 'I am not using a MIME-aware mail reader.\n' 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) themsg = themsg.as_string() # send the message smtp = smtplib.SMTP() smtp.connect() smtp.sendmail(sender, recipients, themsg) smtp.close()
I suspect the issue is this code zips a file as well. I don't want to zip anything as I already have a zipped file I would like to send. In either case, this code is poorly documented as well as the python libraries themselves as they provide no insight on anything past img file and text files.
UPDATE: Error I am getting now. I have also updated what is in my file with the code above
Traceback (most recent call last): File "/Users/Zeroe/Documents/python_hw/cgi-bin/zip_it.py", line 100, in <module> send_file_zipped('hw5.zip', '[email protected]') File "/Users/Zeroe/Documents/python_hw/cgi-bin/zip_it.py", line 32, in send_file_zipped msg.set_payload(myzip.read()) TypeError: read() takes at least 2 arguments (1 given)