import os,re,sys
import _winreg,difflib,filecmp
import smtplib
import socket
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

appName = itsm.getParameter('appName') #provide the Appname here
appName = appName.split(",")
Receiver = itsm.getParameter('EmailTo')  ## Provide an Toemail address where the mail need to be sent. the datatype should be a string.
Sender = itsm.getParameter('EmailFrom')  ## Provide the From Email address from which the mail to be send. the datatype should be a string.
Password = itsm.getParameter('Password')               ##Provide password for from email. the datatype should be a string.
cp_name = os.environ['COMPUTERNAME']
ip = socket.gethostbyname(socket.gethostname())

def gmail(sender_email,password,receiver,text):
    msg = MIMEMultipart()
    msg["From"] = sender_email
    msg["To"] = receiver
    msg["Subject"] = "Application versions details for the Computer Name: %s and IP: %s"%(cp_name,ip)
    attachment = MIMEText(open(text,'r').read(), _subtype="plain")
    attachment.add_header('Content-Disposition', 'attachment', filename='applicationVersions.txt') 
    msg.attach(attachment)
    server = smtplib.SMTP("smtp.gmail.com",587)
    server.starttls()
    server.login(sender_email,password)
    server.sendmail(sender_email, receiver, msg.as_string())
    server.quit()
    print("successfully sent the mail")

li=[]
def collectprograms(rtkey,pK,kA):
    import _winreg
    import os
    try:      
        oK=_winreg.OpenKey(rtkey,pK,0,kA)
        i=0
        while True:
          try:
           bkey=_winreg.EnumKey(oK,i)
           vkey=os.path.join(pK,bkey)
           oK1=_winreg.OpenKey(rtkey,vkey,0,kA)
           try:
            DN,bla=_winreg.QueryValueEx(oK1,'DisplayName')
            DV,bla=_winreg.QueryValueEx(oK1,'DisplayVersion')
            li.append([DN.strip(),DV.strip()])
           except:
            pass
           i+=1
          except:
           break
    except:
        pass
    
    _winreg.CloseKey(oK)
    return li

def programsinstalled():
 uninstallkey='SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall'
 if 'PROGRAMFILES(X86)' in os.environ.keys():
  rklist=[(_winreg.HKEY_LOCAL_MACHINE,uninstallkey,_winreg.KEY_WOW64_32KEY | _winreg.KEY_READ),
      (_winreg.HKEY_LOCAL_MACHINE,uninstallkey,_winreg.KEY_WOW64_64KEY | _winreg.KEY_READ),
      (_winreg.HKEY_CURRENT_USER,uninstallkey,_winreg.KEY_WOW64_32KEY | _winreg.KEY_READ),
      (_winreg.HKEY_CURRENT_USER,uninstallkey,_winreg.KEY_WOW64_64KEY | _winreg.KEY_READ)]
 else:
  rklist=[(_winreg.HKEY_LOCAL_MACHINE,uninstallkey,_winreg.KEY_READ),
      (_winreg.HKEY_CURRENT_USER,uninstallkey,_winreg.KEY_READ)]

 for i in rklist:
  col=collectprograms(i[0], i[1], i[2])
 return col
k=programsinstalled()

fileToSend=os.path.join(os.path.join(os.environ['ProgramData'],'c1_temp'),'installedVersions.txt')
inst_path=r"C:\ProgramData\c1_temp"
if not os.path.exists(inst_path):
    os.makedirs(inst_path)

def write(fileToSend):
    for nm in appName:
        for x,y in k:
            if nm.lower() in x.lower():
                with open(fileToSend, 'a+') as f:
                    f.write(' - '.join([x,y])+"\n")
                    break
        else:
            with open(fileToSend, 'a+') as f:
                f.write('the application %s is not installed on this system'%(nm)+"\n")
                
write(fileToSend)
gmail(Sender,Password,Receiver,fileToSend)
os.remove(fileToSend)