簡體   English   中英

通過電子郵件發送后如何刪除文本文件?

[英]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()

我想在發送后刪除文本文件,但是當我嘗試os.remove(“ C:\\ log.txt”)時,即使server.quit(),它也告訴我log.txt正在使用中,我也剛剛開始編碼所以不要判斷

這是因為您正在打開文件,但是沒有關閉它。

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)

暫無
暫無

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

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