[英]How to delete text file after sending it through email?Python
email_user ='user@gmail.com '
email_send='user@gmail.com'
subject='Python!'
msg= MIMEMultipart()
msg['From']=email_user
msg['To']=email_user
msg['Subject']=subject
body ='hi there,'
msg.attach(MIMEText(body,'plain'))
filename='log.txt'
attachment =open(filename,'rb')
part= MIMEBase('application','octet_stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',"attachment; filename= "+filename)
msg.attach(part)
text= msg.as_string()
server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login(email_user,'password')
server.sendmail(email_user,email_send,text)
server.quit()
i want to delete the text file after sending it, but when i try os.remove("C:\\log.txt") it tells me log.txt is in use even though server.quit() , i also just started coding so dont judge 我想在发送后删除文本文件,但是当我尝试os.remove(“ C:\\ log.txt”)时,即使server.quit(),它也告诉我log.txt正在使用中,我也刚刚开始编码所以不要判断
this is because you are opening a file however you are not closing it. 这是因为您正在打开文件,但是没有关闭它。
attachment =open(filename,'rb')
Following should work. 以下应该工作。
attachment =open(filename,'rb')
part= MIMEBase('application','octet_stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',"attachment; filename= "+filename)
msg.attach(part)
attachment.close()
os.remove(filename)
A better approach should be to read a file using with
context manager. 一个更好的做法应该是阅读使用文件with
上下文管理器。
with open(filename,'rb') as attachment:
part= MIMEBase('application','octet_stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',"attachment; filename= "+filename)
msg.attach(part)
# send message
# remove file
os.remove(filename)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.