python program to rename the file with current date in MMDDYYY format and send email with attachment -
this question has answer here:
- how rename file using python 6 answers
below program send email attachment:
i want rename file student.xlsx
student_mmddyyyy.xlsx
, send email renamed file , after email sent want delete file. how can that?
here code:
import smtplib email.mime.multipart import mimemultipart email.mime.text import mimetext email.mime.base import mimebase email import encoders fromaddr = "myemailid" toaddr = "toaddress" msg = mimemultipart() msg['from'] = fromaddr msg['to'] = toaddr msg['subject'] = "please find attachment" body = "hi" msg.attach(mimetext(body, 'plain')) filename = "student.xlsx" dt = str(datetime.datetime.now()) attachment = open("c:\\users\\prashanth\\desktop\\student.xlsx", "rb") part = mimebase('application', 'octet-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('content-disposition', "attachment; filename= %s" % filename) msg.attach(part) server = smtplib.smtp('smtp.gmail.com', 587) server.starttls() server.login(fromaddr, "password") text = msg.as_string() server.sendmail(fromaddr, toaddr, text) server.quit()
you can use os.rename()
rename file, , os.remove()
remove file. , desired date format can use strftime()
, example:
import os datetime import datetime date_now = datetime.now().strftime('%m%d%y') file_one = "c:\\users\\prashanth\\desktop\\student.xlsx" file_two = 'c:\\users\\prashanth\\desktop\\student_{}.xlsx'.format(date_now) os.rename(file_one, file_two) # send email , attach file # , once you're done: os.remove(file_two)
edit:
you need close()
file before renaming or removing it, or better yet use with-statement
open file , auto close when you're done, example:
attachment = open(file, "rb") part = mimebase('application', 'octet-stream') part.set_payload((attachment).read()) attachment.close()
or
with open(file, "rb") attachment: part = mimebase('application', 'octet-stream') part.set_payload((attachment).read())
Comments
Post a Comment