我想壓縮一個文件夾及其所有的子文件夾/文件,並通過電子郵件將zip文件作爲附件發送。用Python實現這個最好的方法是什麼?我該如何壓縮一個文件夾並用Python通過電子郵件發送壓縮文件?
7
A
回答
20
可以使用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='[email protected]'):
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()
有了這個功能,你可以做:
send_file_zipped('result.txt', ['[email protected]'])
不客氣。
1
0
相關問題
- 1. 如何壓縮數據以通過電子郵件發送
- 2. 壓縮文件列表並附加到電子郵件 - python
- 3. 如何將未壓縮文件夾視爲壓縮文件?
- 4. 從NSIS發送到壓縮(壓縮)文件夾
- 5. Node.js - 壓縮/解壓縮文件夾
- 6. bash:在壓縮其他文件時發送壓縮文件
- 7. 壓縮/壓縮文件夾,同時排除特定文件夾
- 8. 自動粘貼,並通過電子郵件發送一個壓縮文件到PHP沒有用戶輸入
- 9. 壓縮文件通過PS
- 10. 如何使用VBScript將文件夾的每個子文件夾壓縮爲ZIP壓縮文件?
- 11. 如何解壓文件夾並刪除壓縮的原件?
- 12. 爲電子郵件附件壓縮MemoryStream
- 13. HTTP壓縮 - 如何發送EAR文件中存在的預壓縮文件?
- 14. 使用qt壓縮文件夾/文件
- 15. 壓縮/解壓縮文件夾和文件
- 16. 壓縮和解壓縮文件和文件夾
- 17. 如何使用rubyzip解壓縮壓縮文件夾
- 18. 創建一個壓縮(或壓縮)文件夾
- 19. 發送壓縮文件作爲附件
- 20. Android - 解壓縮文件夾?
- 21. Windows.Storage.Compression UnZip壓縮文件夾
- 22. 如何使用ZipKit壓縮文件夾?
- 23. 壓縮文件
- 24. 壓縮一個TIF文件
- 25. 如何壓縮一個文件夾並使用php下載它?
- 26. 上傳壓縮文件,解壓縮並讀取文件
- 27. 如何在asp.net框架4.0中壓縮/解壓縮文件夾
- 28. 通過C#使用cmd來壓縮和解壓縮文件
- 29. Powershell,WMI和壓縮文件/文件夾
- 30. 解壓縮文件夾並從解壓縮文件中獲取圖像
這是一個答案。 – 2008-10-04 00:51:59