简体   繁体   中英

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

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 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM