Attach a zip file in mail python
To attach a ZIP file in a mail using Python, you can use the email
and zipfile
modules. Here's an example:
import email
import zipfile
import smtplib
# Create a ZIP file
with zipfile.ZipFile('example.zip', 'w') as zip_file:
zip_file.write('file1.txt')
zip_file.write('file2.txt')
# Create a message
msg = email.MIMEMultipart()
msg['Subject'] = 'Example ZIP file attachment'
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
# Attach the ZIP file
with open('example.zip', 'rb') as f:
attachment = email.MIMEApplication(f.read())
attachment.add_header('Content-Disposition', 'attachment', filename='example.zip')
msg.attach(attachment)
# Send the email
server = smtplib.SMTP('your_smtp_server')
server.sendmail('[email protected]', '[email protected]', msg.as_string())
server.quit()
This code creates a ZIP file using the zipfile
module, creates an email message using the email
module, attaches the ZIP file to the message, and sends the email using the smtplib
module.
You'll need to replace [email protected]
, [email protected]
, and your_smtp_server
with your actual email address, recipient's email address, and SMTP server, respectively.
Also, make sure to install the email
and smtplib
modules if you haven't already:
pip install email smtplib
Note that this is just an example, and you may need to modify the code to fit your specific use case. For example, you may want to add more attachments, or use a different email client or server.