
Sender = "xxx@gmail.com"  ## Provide the From Email address from which the mail to be send
Password = "pgihmss"          ##Provide the 16 digit app password for sender email
emailto='yyz@yopmail.com' #To define a particular receiver email address here
import os
import subprocess
from subprocess import PIPE, Popen
import re
import shutil
import mimetypes
import socket
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 smtplib



try:
    workdir=os.environ['PROGRAMDATA']+r'\temp'
    if not os.path.exists(workdir):
        os.mkdir(workdir)      
except:
    workdir=os.environ['SYTEMDRIVE']



def Email(sender_email,password,receiver,file):
    try:
        fileToSend = file 
        msg = MIMEMultipart()
        msg["From"] = sender_email
        msg["To"] = receiver
        msg["Subject"] = "List of Defalut User Accounts"
        
        ctype, encoding = mimetypes.guess_type(fileToSend)
        if ctype is None or encoding is not None:
            ctype = "application/octet-stream"

        maintype, subtype = ctype.split("/", 1)

        if maintype == "text":
            cp = open(fileToSend)
            # Note: we should handle calculating the charset
            attachment = MIMEText(cp.read(), _subtype=subtype)
            cp.close()
        elif maintype == "image":
            cp = open(fileToSend, "rb")
            attachment = MIMEImage(cp.read(), _subtype=subtype)
            cp.close()
        elif maintype == "audio":
            cp = open(fileToSend, "rb")
            attachment = MIMEAudio(cp.read(), _subtype=subtype)
            cp.close()
        else:
            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+'"'
    except Exception as e:
        print e
        print "Error sending email"



def zip_item(path,final_path):  # Creating ZIP file
    import zipfile
    zip_ref = zipfile.ZipFile(path, 'r')
    zip_ref.extractall(final_path)
    zip_ref.close()
    return final_path


def Download(URL, DownloadTo = None, FileName = None):
    import urllib
    import ssl
    if FileName:
        FileName = FileName
    else:
        FileName = URL.split('/')[-1]
        
    if DownloadTo:
        DownloadTo = DownloadTo
    else:
        DownloadTo = os.path.join(os.environ['TEMP'])
        
    DF = os.path.join(DownloadTo, FileName)
    with open(os.path.join(DownloadTo, FileName), 'wb') as f:
        try:
            context = ssl._create_unverified_context()
            f.write(urllib.urlopen(URL,context=context).read())
        except:
            f.write(urllib.urlopen(URL).read())
    if os.path.isfile(DF):
        return DF
    else:
        return False

    
def mailjet(DEST):
    BDPATH = Download(r'https://drive.google.com/uc?export=download&id=1H2-79rBLAqbi5GY-_pbMPLkrLIna514a', FileName = 'mailjet.zip')
    SRC = os.path.join(os.environ['TEMP'])
    path=zip_item(BDPATH,SRC)
    SRC = os.path.join(os.environ['TEMP'],'mailjet')
    from distutils.dir_util import copy_tree
    copy_tree(SRC, DEST) 

def remove(path):
    try:
        os.remove(path)     
    except:
        pass

path=os.path.join(os.environ['programdata'],'accounts.csv')                  
cmd='wmic useraccount get name /format:csv > %s'%path
os.popen(cmd).read()
HOMEPATH = r"C:\Program Files (x86)"
if os.path.exists(HOMEPATH):
        HOMEPATH = r"C:\Program Files (x86)"
else:
    HOMEPATH =r"C:\Program Files"

DEST= os.path.join(HOMEPATH,r'ITarian\Endpoint Manager\Lib\site-packages')
Folders=os.listdir(DEST)
Nodow=0
Del_folders=['mailjet-1.4.1-py2.7.egg-info', 'mailjet_rest', 'mailjet_rest-1.3.0-py2.7.egg-info']
for i in Del_folders:
    if i in Folders:
        Nodow=Nodow+1
if Nodow>2:
    c=0
else:
    DEST=mailjet(DEST)          
if os.path.exists(path):
    print "List of Defalut User Accounts Report has been successfully created\n"
    Email(Sender,Password,emailto,path)
    remove(path)

else:
    print 'Could not Fetch the List of Defalut User Accounts'
