
emailto=itsm.getParameter('EmailTo')  ## Provide an To email address where the mail need to be sent.
emailfrom=itsm.getParameter('EmailFrom')  ## Provide the From Email address from which the mail to be send
password=itsm.getParameter('Password')     ##Provide the 16 digit app password for from email


import os
import csv
import socket
computer = ["COMPUTER NAME"]
ip = ["IP ADDRESS"]
def computername():
    return os.environ['COMPUTERNAME']

def ipaddress():
    return socket.gethostbyname(socket.gethostname())

def ecmd(command):
    import ctypes
    from subprocess import PIPE, Popen
    
    class disable_file_system_redirection:
        _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
        _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection
        def __enter__(self):
            self.old_value = ctypes.c_long()
            self.success = self._disable(ctypes.byref(self.old_value))
        def __exit__(self, type, value, traceback):
            if self.success:
                self._revert(self.old_value)
    
    with disable_file_system_redirection():
        obj = Popen(['powershell',command], shell = True, stdout = PIPE, stderr = PIPE)
    out, err = obj.communicate()
    if err:
        print(err)
    else:
        with open("C:\\Windows\\Temp\\output.csv", 'wb') as csvfile:
            cp = 'COMPUTER NAME : '+computername()
            csvfile.write(cp+"\n")
            ip = 'IPADDRESS : '+ipaddress()
            csvfile.write(ip)
            csvfile.write(out)
        return "Success"

app_list = ecmd('$name = (Get-Item env:\Computername).Value; Get-WmiObject win32_Product -ComputerName $name | Select Name,Version,PackageName,Installdate,Vendor | Sort Installdate -Descending')



###Emailing 
if app_list == "Success":
    import os,sys,shutil,re,sys,socket,_winreg,random,getpass
    from datetime import date, datetime
    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
    import ctypes
    from subprocess import PIPE, Popen




    fileToSend=os.path.join(os.environ['TEMP'], 'output.csv')

    def Email(sender_email,password,receiver,file):
        try:
            fileToSend = file 
            msg = MIMEMultipart()
            msg["From"] = sender_email
            msg["To"] = receiver
            msg["Subject"] = '%s %s INV Report!!!!!'%(computername(), ipaddress())
            
            ctype, encoding = mimetypes.guess_type(fileToSend)
            if ctype is None or encoding is not None:
                ctype = "application/octet-stream"

            maintype, subtype = ctype.split("/", 1)

            cp = open(fileToSend, "rb")
            attachment = MIMEBase(maintype, subtype)
            attachment.set_payload(cp.read())
            cp.close()
            encoders.encode_base64(attachment)
            attachment.add_header("Content-Disposition", "attachment", filename=fileToSend)
            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 "Email has been Sent Successfully to the following mail address :"+' "'+emailto+'"'
            os.remove(file)
        except Exception as e:
            print e
            print "Error sending email"
    Email(emailfrom,password,emailto,fileToSend)
else:
    print("something went wrong..")