我正在删除30天之前的几个文件夹,并希望使用gmail自行邮寄所有这些已删除文件夹的列表。
目前它删除文件夹没有任何问题,但电子邮件中的邮件与主题一起为空。我错过了什么?
import os
import time
import shutil
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import encoders
sender = "my_email@gmail.com"
receivers = ["my_email@gmail.com"]
username = 'my_email'
password = 'passwd'
numdays = 86400*30
now = time.time()
directory=os.path.join("/home","/Downloads/trial/")
for r,d,f in os.walk(directory):
for dir in d:
timestamp = os.path.getmtime(os.path.join(r,dir))
if now-numdays > timestamp:
try:
print "removing ",os.path.join(r,dir)
shutil.rmtree(os.path.join(r,dir))
except Exception,e:
print e
pass
else:
print "Deleted folders are: %s" % os.path.join(r,dir)
msg = MIMEMultipart()
msg['To'] = 'my_email@gmail.com'
subject = "Deleted Folders : %s" % os.path.join(r,dir)
msg['Subject'] = subject
try:
mailserver = smtplib.SMTP("smtp.gmail.com", 587)
mailserver.ehlo()
mailserver.starttls()
mailserver.ehlo()
mailserver.login(sender, password)
mailserver.sendmail(sender, to, msg.as_string())
mailserver.close()
print "Successfully Sent email"
except smtplib.SMTPException:
print"Error: Unable to send email"
我收到的电子邮件主题为:已删除的文件夹:/ home / Downloads / trial / 4/4
我的目标是拥有电子邮件的消息/内容/正文,并删除所有文件夹。我在stdout中看到了我想要的输出,即
removing /home/Downloads/trial/1
Deleted folders are: /home/Downloads/trial/1
removing /home/Downloads/trial/2
Deleted folders are: /home/Downloads/trial/2
removing /home/Downloads/trial/3
Deleted folders are: /home/Downloads/trial/3
答案 0 :(得分:1)
试试这个:
deleted_folders = []
for r,d,f in os.walk(directory):
for dir in d:
timestamp = os.path.getmtime(os.path.join(r,dir))
if now-numdays > timestamp:
try:
shutil.rmtree(os.path.join(r,dir))
deleted_folders.append("Deleted folders are: %s" %
os.path.join(r,dir))
# Bad, it's almost never appropriate to catch all Exceptions
# In this case, OSError seems better
except Exception,e:
pass
body = MIMEText("\n".join(deleted_folders), "plain")
msg.attach(body)