我想压缩一个文件夹及其所有子文件夹/文件,并将zip文件作为附件发送电子邮件.用Python实现这一目标的最佳方法是什么?
您可以使用zipfile模块使用zip标准来压缩文件,使用电子邮件模块来创建带附件的电子邮件,使用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'])
别客气.