python程序以MMDDYYY格式重命名具有当前日期的文件,并发送带有附件的电子邮件 [英] python program to rename the file with current date in MMDDYYY format and send email with attachment
问题描述
下面是发送带有附件的电子邮件的程序:
Below is the program to send email with attachment:
我想重命名文件 student.xlsx
到 student_MMDDYYYY.xlsx
并发送带有重命名文件的电子邮件,发送电子邮件后,我要删除该文件。我该怎么办?
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?
这是我的代码:
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()
推荐答案
您可以使用 os.rename()
重命名文件,然后 os.remove()
删除文件。要获得所需的日期格式,可以使用 strftime()
,例如:
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)
编辑:
您需要先 close()
文件,然后重命名或删除它,或者最好使用 with-statement
打开文件。文件并在完成后自动将其关闭,例如:
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()
或
with open(file, "rb") as attachment:
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
这篇关于python程序以MMDDYYY格式重命名具有当前日期的文件,并发送带有附件的电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!