0
我想使用Python3腳本將每天的電子郵件自動化爲一個收件人。該電子郵件應該帶有附件。Python 3 - 附件錯誤
目前我正在嘗試下面的Python 3.5代碼,其中令人難以置信的只能運行一次。
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
fromaddr = "[email protected]"
toaddr = "[email protected]"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Daily report"
body = "Email text"
msg.attach(MIMEText(body, 'plain'))
filename = 'DAILY REPORT.xls'
attachment = open('Z:\\DAILY REPORT.xls', "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment).read()
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
server = smtplib.SMTP('smtp.server.biz', 25)
server.starttls()
server.login(fromaddr, "apasswordhere")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
第一次運行(並收到電子郵件+附件)後,它似乎不再有效。我公司不斷獲得唯一的例外是:
Traceback (most recent call last):
File "Z:/main.py", line 23, in <module>
part.set_payload(attachment).read()
AttributeError: 'NoneType' object has no attribute 'read'
請注意,是在遠程NAS的文件被附加到電子郵件messange和Python腳本,本地monted爲Z:在Windows Server 2012上 在此係統我安裝了Pyton2和Python3兩個不同的目錄。當從consolle調用python.exe時,我的系統在Python2上默認,但是如果我用Python3運行我的腳本,我會得到同樣的錯誤。 也在我的編輯器中運行腳本(Pyecharm在Python3控制檯上默認)會引發相同的錯誤。
作爲實在不明白,我會感謝任何意見,以解決我的錯做
你期望行'part.set_payload(attachment).read ()'做什麼?它看起來像你的第一個'''末尾:'part.set_payload(attachment.read())' – jwodder
感謝您的幫助,您的評論解決了我的問題。我無法看到我的錯誤。 –
@J_CsT:如果你找到了你的問題的答案,然後張貼答案並接受它。它對每個人都有好處。 –