通过电子邮件发送后如何删除文本文件?

时间:2019-03-19 18:45:45

标签: 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()

我想在发送后删除文本文件,但是当我尝试时 os.remove(“ C:\ log.txt”)它告诉我log.txt在使用中,即使 server.quit(),我也刚刚开始编码,所以不要判断

1 个答案:

答案 0 :(得分:1)

这是因为您正在打开文件,但是没有关闭它。

attachment =open(filename,'rb')

以下内容应该有效。

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)

更好的方法应该是使用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)