问题
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()
回答1:
You can use os.rename()
to rename a file, and os.remove()
to remove a file. And to get the desired date format you can use strftime()
, for example:
import os
from 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 your email and attach the file
# and once you're done:
os.remove(file_two)
EDIT:
You need to close()
the file before renaming or removing it, or better yet use with-statement
to open the file and auto close it when you're done, for example:
attachment = open(file, "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
attachment.close()
or
with open(file, "rb") as attachment:
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
来源:https://stackoverflow.com/questions/45690763/python-program-to-rename-the-file-with-current-date-in-mmddyyy-format-and-send-e