[英]Attaching file in Python email
因此,我嘗試了多種方法將文件(尤其是CSV文件)附加到python中的電子郵件並發送。 我的文本電子郵件正常工作,我確實收到了一個CSV文件,只是一個空文件。 我目前正在發送附件,如下所示:
ctype, encoding = mimetypes.guess_type("results.csv")
if ctype is None or encoding is not None:
ctype = "application/octet-stream"
maintype, subtype = ctype.split("/", 1)
# organizing receivers
receiver = receivers.split(',')
# creating subject
subject = 'BLAH BLAH'
timestamp = time.strftime("%m/%d/%Y:%H:%M:%S")
subject += str(timestamp)
# form email
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = " ".join(receivers)
msg['Subject'] = subject
msg['Message-Id'] = make_msgid()
msg['Date'] = formatdate(localtime=True)
msg.attach(MIMEText(msgstr, 'plain'))
if maintype == "text":
fp = open("results.csv")
attachment = MIMEText(fp.read(), _subtype=subtype)
fp.close()
else:
fp = open('results.csv', "rb")
attachment = MIMEBase(maintype, subtype)
attachment.set_payload(fp.read())
fp.close()
encoders.encode_base64(attachment)
attachment.add_header("Content-Disposition", "attachment", filename='results.csv')
msg.attach(attachment)
try:
smtpobj = smtplib.SMTP('smtp.gmail.com:587')
smtpobj.ehlo()
smtpobj.starttls()
smtpobj.ehlo()
smtpobj.login(username, password)
smtpobj.sendmail(sender, receiver, msg.as_string())
smtpobj.quit()
except smtplib.SMTPException:
print 'Error: unable to send mail'
這類似於此處的答案: python無法通過電子郵件發送附件文件我也嘗試過類似以下的簡單方法: 如何使用Python發送電子郵件附件 https://docs.python.org/2/library/email.html
和其他,但沒有成功。 如何發送完整的附件?
因此,經過大量調試后,我意識到在嘗試再次讀取該文件以構成電子郵件之前,我沒有正確關閉該文件。 我有類似下面的代碼:
with open('results.csv', "rb") as csvfile:
#compose the csv file
#blah
#blah
#blah
#then I called my email function but the file hadn't yet been closed and I was trying to reopen.
為了解決這個問題,我只是簡單地在with
語句之外調用了我的email函數來關閉文件。
with open('results.csv', "rb") as csvfile:
#compose the csv file
#blah
#blah
#blah
send_the_email()
我希望這可以防止其他人像我一樣浪費時間在簡單的事情上。
嘗試這樣編輯此部分
else:
with open('results.csv', "rb") as fp:
fp.seek(0)
attachment = MIMEBase(maintype, subtype)
attachment.set_payload(fp.read())
encoders.encode_base64(attachment)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.