I am deleting several folders which are 30 days old and want to mail myself the list of all those deleted folders using gmail.
Currently it deletes the folder without any trouble but the message in the email is blank along with subject. What am I missing?
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"
I am receiving the email with subject as : Deleted Folders : /home/Downloads/trial/4/4
My objective was to have a message/content/body of the email, with all the folders deleted. I see the output I want in the stdout i.e
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
Try this:
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)