emailto=['xxxx@gmail.com']  ## Provide an Toemail address where the mail need to be sent.You can also provide any number of To eamil address For example: ['tamil@yopmail.com','sensor@yopmail.com']
emailfrom='xxxx@gmail.com' ## Provide the From Email address from which the mail to be send
password='xxxxx'               ##Provide password for from email
smtpserver='smtp.gmail.com'
port=587

msgbody=r'''Hi

This Device remaining size is less than 10 GB after performed cleanup.

Thank you.'''

import os
import re
import ctypes
from subprocess import PIPE, Popen
import socket
import smtplib
import mimetypes
from email.mime.multipart import MIMEMultipart
from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from datetime import datetime, date
import json
import sys
import shutil
import time
########################################Packages##############################################
start=time.time()
def alert(arg):
    sys.stderr.write("%d%d%d" % (arg, arg, arg))

def computername():
    return os.environ['COMPUTERNAME']

def ipaddress():
    return socket.gethostbyname(socket.gethostname())

subject='%s %s Alert : Device Size Less Than 10 GB!!!!!'%(computername(), ipaddress())


def emailreport(subject, emailto,emailfrom,password,smtpserver,port,msgbody):
    msg = MIMEMultipart()
    msg["From"] = emailfrom
    msg["To"] = ",".join(emailto)
    msg["Subject"] = subject
    msg.preamble = subject
    body = MIMEText(msgbody)
    msg.attach(body)       
    try:
        server = smtplib.SMTP(smtpserver,port)
        server.ehlo()
        server.starttls()
        server.login(emailfrom, password)
        server.sendmail(emailfrom, emailto, msg.as_string())
        server.quit()
        return " \nThe email report has been sent to "+msg["To"]
    except Exception as e:
        return e

def convert_bytes(size, unit=None):
    if unit == "KB":
        return (str(round(size / 1024, 3)))
    elif unit == "MB":
        return (str(round(size / (1024 * 1024), 3)))
    elif unit == "GB":
        return (str(round(size / (1024 * 1024 * 1024), 3)))
    else:
        return (str(size))

def permissions(dirpath):
    mode=0o777
    if os.path.isdir(dirpath):
        try:
            for root,dirs,files in os.walk(dirpath,topdown=False):
                for dircs in [os.path.join(root,d) for d in dirs]:
                    os.chmod(dircs,mode)
                for s_file in [os.path.join(root,f) for f in files]:
                    os.chmod(s_file,mode)
        except Exception as E:
            print "File being Used %s"%E
########################################Funtions##############################################           
process=Popen('wmic logicaldisk get size,freespace,caption',stdout=PIPE,stderr=PIPE)
res,err=process.communicate()
harddisk=re.findall("C:.+",res)[0].split()
caption=harddisk[0]
freespace=int(harddisk[1])
#totalspace=int(harddisk[2])
try :
    re_size=convert_bytes(freespace,unit='GB')
    re_size=float(re_size)
    if re_size<10.0:
        alert(1)
        print "Space is less than 10 GB clearing Temp Files"
        print "Removing Users Temp Files"
        users=os.popen("net user").read().split()[5:-5]
        fil_users=[i for i in users if i!='Guest' and i!='DefaultAccount']
        fil_user_temp_path=["C:\\Users\\"+i+"\\AppData\\Local\\Temp" for i in fil_users ]
        for i in fil_user_temp_path:
            if os.path.exists(i):
                print "Providing permission %s "%i
                permissions(i)
                print "Cleaning %s"%i
                shutil.rmtree(i,ignore_errors=True)
            else:
                pass
        print "Provinding Permission C:\Windows\Temp"
        permissions("C:\Windows\Temp")
        print("Cleaning C:\Windows\Temp")
        shutil.rmtree("C:\Windows\Temp",ignore_errors=True)
        print "Cleared Temp Files\n"

        fil_logs=os.popen('powershell.exe "Get-EventLog -LogName * | Select-Object -Property Log"').read().splitlines()[3:-2]
        for i in fil_logs:
            print "Clearing Logs of %s"%i
            os.popen("wmic nteventlog where filename=%s cleareventlog"%i).read()
        print "Logs Cleared"
    else:
        alert(0)
        print "Still contains %s GB in %s"%(re_size,caption)
except Exception as E:
    print E

process=Popen('wmic logicaldisk get size,freespace,caption',stdout=PIPE,stderr=PIPE)
res,err=process.communicate()
harddisk=re.findall("C:.+",res)[0].split()
caption=harddisk[0]
freespace=int(harddisk[1])
#totalspace=int(harddisk[2])
try :
    re_size=convert_bytes(freespace,unit='GB')
    re_size=float(re_size)
    if re_size<10.0:
        print emailreport(subject,emailto,emailfrom,password,smtpserver,port,msgbody)
        print 'mail sent'
except Exception as E:
    print E
finally:
    print "Executed in %s seconds "%(time.time()-start)
    
