This question already has an answer here:
- How to rename a file using Python 10 answers
Below is the program to send email with attachment:
I want to rename the file student.xlsx
to student_MMDDYYYY.xlsx
and send email with renamed file and after email is sent I want to delete that file. How can I do that?
Here is my code:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
fromaddr = "MYEMAILID"
toaddr = "TOADDRESS"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Please find the 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()