簡體   English   中英

通過電子郵件發送的郵政編碼首次嘗試無效

[英]Zip sent via email is invalid on first attempt

我嘗試創建一個zip存檔,其中包含來自特定目錄(和子目錄)的所有文件,並通過郵件發送:

#Create archive containing all files from directory "reports/"
zipf = zipfile.ZipFile('reports.zip', 'w')
for root, dirs, files in os.walk('reports/'):
for file in files:
    zipf.write(os.path.join(root, file))

#Create email
msg = MIMEMultipart()
msg["From"] = emailfrom
msg["To"] = emailto
msg["Subject"] = "Monatliche Reports - Verrechnung an Kunden"

#Attach report.zip to email
fp = open(fileToSend, "rb")
attachment = MIMEBase('application', 'zip')
attachment.set_payload(fp.read())
fp.close()
encoders.encode_base64(attachment)
attachment.add_header("Content-Disposition", "attachment",
filename=fileToSend)
msg.attach(attachment)

#Send email via localhost smtp-server
server = smtplib.SMTP("localhost")
server.sendmail(emailfrom, emailto, msg.as_string())
server.quit()

該腳本似乎有效。 我收到包含所有文件的zip存檔的郵件。 執行腳本時,有兩種可能的情況:

情況1:執行腳本之前已經有一個zip存檔,名為report.zip(上次運行的舊存檔)

情況2:執行腳本之前沒有zip存檔。

在第一種情況下,一切正常。 舊的將被新生成的替換,然后將通過電子郵件發送。

在情況2中,report.zip是通過電子郵件生成並發送的,但是無效。 如果我嘗試在Windows上使用7zip(或Windows板載工具)打開它,則只說“檔案無效”。 我發現只有通過電子郵件發送的report.zip損壞了。 如果我通過電子郵件手動發送在案例2中生成的report.zip,則可以將其解壓縮並使用文件。

我是python新手,說實話,要達到目前的水平已經很困難了,但是解決這個問題令我頭疼。 誰能解釋我在做什么錯?

添加文件后,您需要關閉zip文件,以確保存檔完整。

https://docs.python.org/2/library/zipfile.html#zipfile.ZipFile.close

最好使用with語句:

with zipfile.ZipFile('reports.zip', 'w') as zipf: 
   for root, dirs, files in os.walk('reports/'):
      for file in files:
         zipf.write(os.path.join(root, file))    

詳細信息據我了解。

第一輪

  • zipfile創建一個文件描述符(在內存占位符中)和一個包清單(要添加的文件)
  • zipfile.write()將文件壓縮到文件描述符中,並將文件添加到清單中
  • msg.attach()文件尚未刷新,因此內存中仍沒有任何內容。
  • --end腳本文件描述符清理將文件描述符刷新到磁盤。 (report.zip存在,但不完整/無效)

第二輪

  • zipfile創建一個fd和清單
  • zipfile.write()將文件壓縮到fd並將文件添加到清單
  • msg.attach()文件上次刷新,但仍不完整。 附加無效文件

嘗試這個:

import yagmail
me = 'me@gmail.com'
yag = yagmail.SMTP(emailfrom, 'mypassword') 
yag.send(emailto,  "Monatliche Reports - Verrechnung an Kunden", 'reports.zip')

您可能必須使用pip install yagmail

免責聲明:我是yagmail的開發人員,該軟件包試圖使發送電子郵件(帶有或不帶有附件)變得容易。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM