如何在Python中压缩文件夹并发送压缩文件?
我想把一个文件夹以及里面所有的子文件夹和文件压缩成一个zip文件,然后通过邮件把这个zip文件作为附件发送出去。用Python实现这个功能,最好的方法是什么呢?
3 个回答
19
你可以使用 zipfile 模块来压缩文件,这个模块是按照 zip 标准来工作的;然后用 email 模块来创建带有附件的邮件;最后用 smtplib 模块来发送邮件。这一切都可以仅仅通过标准库来完成。
Python - 自带工具
如果你不想自己编程,而是想在 stackoverflow.org 上问问题,或者(正如评论中提到的)不想加 homework
标签,那好吧,这里有个解决方案:
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='you@you.com'):
zf = tempfile.TemporaryFile(prefix='mail', suffix='.zip')
zip = zipfile.ZipFile(zf, 'w')
zip.write(the_file)
zip.close()
zf.seek(0)
# 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()
"""
# alternative to the above 4 lines if you're using gmail
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.login("username", "password")
server.sendmail(sender,recipients,themsg)
server.quit()
"""
使用这个函数,你只需要这样做:
send_file_zipped('result.txt', ['me@me.org'])
不客气。