def main():
    test = False

    #recipients = {}
    #recipientsFile = open('C:' + os.sep + 'PythonScripts' + os.sep + 'SelinaReports' + os.sep + 'recipients.txt', 'r')

    #pairs = recipientsFile.readlines()
    
    dateFolder = str(datetime.date.today())    
    dateFolder = dateFolder[:4] + dateFolder[5:7] + dateFolder[8:10]
  
    #create the name of the output directory
    EOD_ReportsFolder = 'C:\\EOD-Reports\\Montrica\\'
    todaysFolder = '%s%s' %(EOD_ReportsFolder, dateFolder) 
    #find all the reports generated on a given day
    Reports = os.listdir(todaysFolder) 

    #add the path to the beginning of every report name
    todaysReports = []
    for report in Reports:
        todaysReports.append(todaysFolder + os.sep + report)   

    #email the reports to everyone in the list sendTo
    if not test:
        sendTo = ['email',\
                ]
    else:
        sendTo = ['email']

    Email.notify(sendTo\
                 ,'EOD Reports Delivery for Montrica'\
                 ,'Please find a copy of today\'s reports attached.'\
                 ,files=todaysReports)
	def run(self, dispatcher, tracker, domain):
		mail_confirmation = tracker.get_slot('mailConfirm')
		mailId = tracker.get_slot('emailId')
		loc = tracker.get_slot('location')
		if mail_confirmation.lower() == "yes":
			if mailId == None or mailId == "":
			    mailId = input("To what email id should I send it to? \n")
			is_valid = validate_email(mailId)
			if is_valid == False:
			    dispatcher.utter_message("Invalid email id")
			    return [SlotSet('location',loc)]
			d = do_search(dispatcher, tracker, domain, 10)
			response=""
			if d['results_found'] == 0:
			    response= "no results found"
			else:
			    response = response+ "Found below restaurants" +"\n"
			    count = 1
			    for restaurant in d['restaurants']:
			        response = response + str(count) + ") " + restaurant['restaurant']['name'] + "\n"
			        response = response + "   Address: " + restaurant['restaurant']['location']['address'] + "\n"
			        response = response + "   Average budget for two people: " + str(restaurant['restaurant']['average_cost_for_two']) + "\n"
			        response = response + "   Rating: " + str(restaurant['restaurant']['user_rating']['aggregate_rating']) + "\n"
			        count = count + 1
			Email.send_mail(mailId, response)
			response= "Sent"
		else:
			response= ""
		
		dispatcher.utter_message(""+response)
		return [SlotSet('location',loc)]
Example #3
0
    def initiate_reset(self, data):
        # Validate data
        needed = ["email", "password"]
        for item in needed:
            if item not in data:
                return False
        if data["password"]:  # Attempt to keep bots at bay
            return False

        # Find user
        email = data["email"].lower()
        cursor = self.__database.cursor()

        # Send mail
        for row in cursor.execute(self.__user_select +
                              "WHERE email=?", (email, )):
            user = User(*row)
            assert user
            translator = user.get_dictionary()
            timeout = int(translator.get("_reset_expiration_user_"))
            (sid, expires) = self.__create_session(exp_minutes=timeout)
            cursor.execute(self.__session_insert,
                     (sid, email, self.SESSION_RESET, expires))
            logging.debug("Initiate reset for " + email)
            mail = Email(user.get_email(), translator, "_reset_subject_")
            variables = {"__reset_link": sid, "__name": user.get_name()}
            mail.load_body("reset", variables)
            mail.run()

            self.__database.commit()
            return True

        logging.debug("Reset failed")
        return False
def sendReportToRecipient(name, listOfFiles, subject, msg, test=True, pairs={}):
    Email.notifyWithBCC(pairs[name][0]\
                            ,pairs[name][1]\
                            ,pairs[name][2]\
                            ,subject\
                            ,msg\
                            ,listOfFiles)
Example #5
0
def freeChampPollTest():
    subject = "Free Champion Notification"
    emails = [email[0] for email in query_db("SELECT Distinct Notify.Email FROM Notify JOIN Champs ON Champs.Champ = Notify.Champ WHERE Champs.Free = 1")]
    print emails
    for email in emails:
        freeChampsSelectedByUser = [champ[0] for champ in query_db("""
            SELECT champs.champ
            FROM CHAMPS
            JOIN notify ON champs.champ = notify.champ
            where notify.email=(?) and champs.free = 1 order by champs.champ""", (email,))]

        msg = "Hello from Free Champ! You wished to be notified when the below champs are free: \n"
        htmlChamps = ""
        for champ in freeChampsSelectedByUser:
            msg += champ + '\n'
            htmlChamps += champ + '\n'
        token = getToken(email)
        url = "http://" + app.config['HOST'] + ":" + str(app.config['PORT']) + "/optOut?token=" + token
        msg += "\n\n" + url

        #HTML version
        htmlMsg = """<html>
        <p>Hello from Free Champ! You wished to be notified when the below champs are free: \n</p>""" + htmlChamps \
        +  "<br><br><a href=" + url + ">Opt-Out</a> </html>"




        Email.sendEmail(email, subject, msg, htmlMsg)

    return "OK"
Example #6
0
def main(users, \
         start, \
         end, \
         whereToLook = None, \
         pattern = r", RETR",\
         email = False):
    if whereToLook == None:
        whereToLook = "\\\\fcpap01.fcproduction.local\\G6Log\\firstcoverage.com-transfers-%s.log" % end
    
    while end >= start:
        print end
        #print whereToLook
        for user in users:
            ##if os.path.isfile(downloads):
            ##    f = open(downloads)
            find = r"%s%s" % (user, pattern)
            print user
            mainpattern = re.compile(find, re.I)
            try:
                QuantCharterCheck.processFile(whereToLook, mainpattern, datetime.date.today(), validateOnly=True)
            except IOError:
                pass 
            print
            end -= datetime.timedelta(days=1)    
            whereToLook = "\\\\fcpap01.fcproduction.local\\G6Log\\firstcoverage.com-transfers-%s.log" % end

    if email:
        #Still need to build the email body with downloaders
        Email.notify()
def notice(name=None, error=False, errorstring=None):
    email_to_addr = manager.getValue(sectionHeader=name, key='emailto')
    sms_to_addr = manager.getValue(sectionHeader=name, key='smsto')
    subject_name = 'MySQL主从检测'
    if error:
        if errorstring:
            email_content = subject_name + ':' + name + errorstring
        else:
            email_content = subject_name + ':' + name + '出错'
        Email.sendMail(subject=subject_name,
                       to_addr=email_to_addr,
                       content=email_content)
        SmsAlidayu.sendSMS(to_phone=sms_to_addr,
                           product_name=subject_name,
                           error=True,
                           message=email_content)
    else:
        email_content = subject_name + ':' + name + '恢复正常'
        subject_name += name
        Email.sendMail(subject=subject_name,
                       to_addr=email_to_addr,
                       content=email_content)
        SmsAlidayu.sendSMS(to_phone=sms_to_addr,
                           product_name=subject_name,
                           error=False)
Example #8
0
class Motor:
    #its just how it goes
    def __init__(self, servoPin, htz, startAngle):
        self.email = Email(465, '*****@*****.**',
                           'AutoCatProject')
        self.htz = htz
        self.servoPin = servoPin
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(self.servoPin, GPIO.OUT)
        self.p = GPIO.PWM(self.servoPin, self.htz)
        self.startAngle = startAngle
        self.p.ChangeDutyCycle(self.startAngle)

    def feed(self, toAngle, timeToRun):
        print("Feeding now")
        self.p.ChangeDutyCycle(toAngle)
        time.sleep(timeToRun)
        self.p.ChangeDutyCycle(self.startAngle)
        time.sleep(0.5)
        feedingMessage = 'Feeding complete on: ' + str(datetime.datetime.now())
        print(feedingMessage)
        self.email.sendEmail('*****@*****.**', 'Feeding Complete!')
        self.email.sendEmail('*****@*****.**', 'Feeding Complete!')
        print("Feeding Complete")

    def end(self):
        self.p.stop()
        GPIO.cleanup()
Example #9
0
    def listen(self):
        (clientsocket, address) = self.serversocket.accept()
        while True:
            #(clientsocket, address) = self.serversocket.accept()
            print("Connection found")
            try:
                data = clientsocket.recv(1024).decode("utf-8")
                print(data)
                processed_action = data.split(",")
                function = processed_action[0]
                myinput = processed_action[1]
                print("My input: "+ myinput)

                if function == "Stock":
                    stock_info = stock.findStock(myinput)
                    clientsocket.send((stock_info + "\n").encode("utf-8"))
                    print("Sent stock information " + stock_info )
                elif function == "Email":
                    #Read text file, write input from Unity into text file
                    #message = processed_action[2]
                    email.emailBody(myinput)
                    email.main()
                    confirmation = "Email has been sent"
                    #clientsocket.send(confirmation.encode("utf-8"))
                elif function == "Call":
                    #Read in message if user calls or sends message
                    #message = processed_action[2]
                    #cm.outgoingCall(myinput,message)
                    cm.outgoingCall(myinput)
                    confirmation = "Called Phone"
                    #clientsocket.send(confirmation.encode("utf-8"))
                elif function == "SMS":
                    message = processed_action[2]
                    cm.sendMessage(myinput,message)
                    confirmation = "SMS message has been sent"
                    #clientsocket.send(confirmation.encode("utf-8"))
                elif function == "Definition":
                    grammar.Definition(myinput)
                    confirmation = "Found defintion"
                    #clientsocket.send(confirmation.encode("utf-8"))
                elif function == "Synonym":
                    grammar.Synonym(myinput)
                    confirmation = "Found synonym"
                    #clientsocket.send(confirmation.encode("utf-8"))
                elif function == "Pizza":
                    myOrder = pizza.parseHololensOrder(myinput)
                    pizza.placeOrder(myOrder)
                    confirmation = "Ordered Pizza (with TBD)"
                    #clientsocket.send(confirmation.encode("utf-8"))
                '''elif function == "Light":
                    lights.turnOn()
                    confirmation = "Adjust Hue Light"
                    #clientsocket.send(confirmation.encode("utf-8"))
                elif data == "ping":
                    print ("Unity Sent: " + str(data))
                    #clientsocket.send("pong")
                print("closed socket")'''
            finally:
                clientsocket.close()
Example #10
0
def doMerge(email=None, key=None):
    """
Merge two accounts together. Will send a confirmation mail to the to-be-merged email.
"""

    tmpl = lookup.get_template('profile.html')

    errors = ''
    if key is not None and isValidMergeUrlKey(key):

        newMail = getUserFromPassword(key[:8])
        oldMail = getUserFromPassword(key[8:])

        log.info('valid merging key, merging "' + newMail + '" and "'
                 + oldMail + '" now')
        if mergeUser(newMail, oldMail):
            tmpl = lookup.get_template('index.html')
            return tmpl.render(good_news='Merge was successful!')
        else:
            log.warning('couldn\'t merge "' + newMail + '" and "'
                        + oldMail + '" for some unexpected reason')
            return tmpl.render(feedback='Oh no! Something went wrong. Please try again later.'
                               )
    elif email is not None:

        log.info('merge "' + email.lower() + '" with "'
                 + getCurrentUserName() + '"')
        if emailRegex.match(email) == None:
            errors += '<li>Your email is invalid</li>'
        elif not userExists(email, True):
            errors += '<li>' + str(email.lower()) \
                + ' doesn\'t exist</li>'
        if userExists(getCurrentUserName()):
            events = listAllEventsFor(getCurrentUserName())
            for event in events:
                if str(event.participants).find(email) != -1:
                    log.info('found instance where "' + email.lower()
                             + '" and "' + getCurrentUserName().lower()
                             + '" are listed as hoster and participant. Can\'t merge'
                             )
                    errors = \
                        '<li>Can\'t merge these two accounts, because there are events, where host and participant are the same person.</li>'
                if str(event.owner).find(email) != -1:
                    log.info('found instance where owner and to-be-merged user are the same'
                             )
                    errors = '<li>Can\'t merge two same accounts.</li>'
        if not errors == '':
            return tmpl.render(bad_news='<ul>' + errors + '</ul>')
        else:
            mergeKey = getMergeUrlKey(getCurrentUserName(), email)
            Email.mergeRequest(getCurrentUserName(), email, mergeKey)

            return tmpl.render(good_news='An email has be sent to "'
                               + email.lower()
                               + '" for further information')
    else:
        tmpl = lookup.get_template('index.html')
        return tmpl.render(bad_news="Something went wrong, merge wasn't successful (maybe you already merged?)"
                           )
Example #11
0
def checkConnection():
    if os.path.isfile("\\\\fcpap01.fcproduction.local\\G6Log\\firstcoverage.com-transfers-%s.log" % start):
        f = open("\\\\fcpap01.fcproduction.local\\G6Log\\firstcoverage.com-transfers-%s.log" % start)
        f.close()
    else:
        print 'Error: Cannot reach remote file'
        Email.notify('email', 'Problem Running QuantChartercheck on FCPUTIL01', 'Error: Cannot reach remote file')
        exit(1)
Example #12
0
    def Begin_Imaging(self):
        global jpg, directory, name, duration, interval, total, file, on_flag, file_list
        
        if (on_flag == False): 
            self.Image_Thread = Image()
            self.Dropbox_Thread = Dropbox()
            self.Email_Thread = Email()
            total = int((duration*60)/interval)
            self.Progress_Bar.setMaximum(total)
            
            if(not os.path.isdir(directory)):
                os.mkdir(directory)
            
            if (self.JPG.isChecked()):
                file = directory + "/" +name + "_%04d.jpg"
            else:
                file = directory + "/" +name + "_%04d.png"
            self.Image_Thread.started.connect(lambda: self.Start_Image())
            self.Image_Thread.finished.connect(lambda: self.Done())
            self.Image_Thread.capture.connect(lambda: self.Progress())
            self.Image_Thread.check_point.connect(lambda: self.Check_Point())
            self.Image_Thread.imaging_running.connect(lambda: self.Imaging_Running())
            self.Image_Thread.imaging_running_done.connect(lambda: self.Imaging_Running_Complete())

            self.Image_Thread.start()

            if(self.Cloud_Sync.isChecked()):
                self.Dropbox_Thread.start()
                self.Email_Thread.start()

            on_flag = True
        
        else:
            self.Image_Thread.terminate()
            self.IST_Editor.setEnabled(True)
            self.ICI_spinBox.setEnabled(True)
            self.ISD_spinBox.setEnabled(True)
            self.Live_Feed.setEnabled(True)
            self.Storage_Directory.setEnabled(True)
            self.Snapshot.setEnabled(True)
            self.JPG.setEnabled(True)
            self.PNG.setEnabled(True)
            self.Dropbox_Email.setEnabled(True)
            self.Dropbox_Confirm.setEnabled(True)
            self.Frequency_Off.setEnabled(True)
            self.Frequency_Low.setEnabled(True)
            self.Frequency_Average.setEnabled(True)
            self.Frequency_High.setEnabled(True)
            self.Image_Frame.setPixmap(QtGui.QPixmap("../_image/background.png"))
            icon3 = QtGui.QIcon()
            icon3.addPixmap(QtGui.QPixmap("../_image/Start-icon.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
            self.Start_Imaging.setIcon(icon3)
            self.Start_Imaging.setText("Start Image Sequence")
            self.Progress_Bar.setValue(0)
            del file_list[:]
            self.Image_Thread.terminate()
            self.Dropbox_Thread.terminate()
            on_flag = False
Example #13
0
 def __init__(self, servoPin, htz, startAngle):
     self.email = Email(465, '*****@*****.**',
                        'AutoCatProject')
     self.htz = htz
     self.servoPin = servoPin
     GPIO.setmode(GPIO.BCM)
     GPIO.setup(self.servoPin, GPIO.OUT)
     self.p = GPIO.PWM(self.servoPin, self.htz)
     self.startAngle = startAngle
     self.p.ChangeDutyCycle(self.startAngle)
Example #14
0
 def testing(self):
     lista = []
     lista.append(Email.Email("alumno", "poo", "com"))
     print(lista[0].retornaEmail())
     lista.append(Email.Email().CrearCuenta("alumnogmail.com"))
     print(lista[-1])
     lista.append(Email.Email().emailbyname("Nombre Apellido", "gmail",
                                            "com"))
     print("{}".format(lista[-1].retornaEmail()))
     print(lista[-1].getpassword == "1236")
Example #15
0
    def doMerge(self, email=None, key=None):
        """
    Merge two accounts together. Will send a confirmation mail to the to-be-merged email.
    """

        tmpl = lookup.get_template("merge.html")

        errors = ""
        if key is not None and isValidMergeUrlKey(key):

            newMail = getUserFromPassword(key[:8])
            oldMail = getUserFromPassword(key[8:])

            log.info('valid merging key, merging "' + newMail + '" and "' + oldMail + '" now')
            if mergeUser(newMail, oldMail):
                return self.index()
            else:
                log.warning("couldn't merge \"" + newMail + '" and "' + oldMail + '" for some unexpected reason')
                return tmpl.render(
                    feedback="Oh no! Something went wrong. Please try again later.", newUser=getCurrentUserName()
                )
        else:

            log.info('merge "' + email.lower() + '" with "' + getCurrentUserName() + '"')
            if email is None:
                errors += "<li>You have to provide an email address</li>"
            if emailRegex.match(email) == None:
                errors += "<li>Your email is invalid</li>"
            elif not userExists(email, True):
                errors += "<li>" + str(email.lower()) + " doesn't exist</li>"
            if userExists(getCurrentUserName()):
                events = listAllEventsFor(getCurrentUserName())
                for event in events:
                    if str(event.participants).find(email) != -1:
                        log.info(
                            'found instance where "'
                            + email.lower()
                            + '" and "'
                            + getCurrentUserName().lower()
                            + "\" are listed as hoster and participant. Can't merge"
                        )
                        errors = "<li>Can't merge these two accounts, because there are events, where host and participant are the same person.</li>"
                    if str(event.owner).find(email) != -1:
                        log.info("found instance where owner and to-be-merged user are the same")
                        errors = "<li>Can't merge two same accounts.</li>"
            if not errors == "":
                return tmpl.render(bad_news="<ul>" + errors + "</ul>", newUser=getCurrentUserName())
            else:
                mergeKey = getMergeUrlKey(getCurrentUserName(), email)
                Email.mergeRequest(getCurrentUserName(), email, mergeKey)

                return tmpl.render(
                    good_news='An email has be sent to "' + email.lower() + '" for further information',
                    newUser=getCurrentUserName(),
                )
Example #16
0
    def doAddAlias(self, alias=None, mainMail=None, key=None):
        """
        Add an alias to this account.
        """

        tmpl = lookup.get_template("alias.html")
        errors = ""

        if key is not None and isValidMergeUrlKey(key):
            mainMail = getUserFromPassword(key[:8])
            alias = getUserFromPassword(key[8:])

            log.info('valid alias key, add "' + alias + '" as alias to "' + mainMail)

            if mergeUser(mainMail, alias):
                addAlias(mainMail, alias)
                return tmpl.render(good_news="Your alias has been added")
            else:
                log.warning("couldn't alias/merge \"" + newUser + '" and "' + oldUser + '" for some unexpected reason')
                return tmpl.render(
                    bad_news="Oh no! Something went wrong. Please try again later.", newUser=getCurrentUserName()
                )
        elif alias is not None:
            log.info("alias is not not")

            alias = [x.strip() for x in alias.split(",")]
            for user in alias:
                if emailRegex.match(user) == None:
                    errors += "<li>" + user + " is invalid</li>"
                else:

                    if userExists(user, True):
                        errors += (
                            "<li>" + user + ' already exists, use <a href="../merge">Merge E-Mails</a> instead</li>'
                        )
                    elif aliasUserExists(user):
                        errors += "<li>" + user + " is already an alias for someone else</li>"

            if not errors == "":
                return tmpl.render(bad_news="<ul>" + errors + "</ul>")
            else:

                info = ""
                for user in alias:
                    if activateUser(user, "Alias for " + user, "random", True):
                        log.info("register " + user + " for the purpose of adding as alias")
                        aliasKey = getMergeUrlKey(getCurrentUserName(), user)

                        Email.aliasRequest(getCurrentUserName(), user, aliasKey)
                        info += '<li>An email has been sent to "' + user.lower() + '" for further information</li>'

                return tmpl.render(good_news=info)
        else:

            return tmpl.render(good_news="Nothing to add to aliases list")
Example #17
0
def log_error(err_msg, shutdown=False):
    __log("ERROR ------------------------------------------------------")
    __log(err_msg)
    if shutdown:
        __log("Shutting down...")
    __log("------------------------------------------------------------")
    errors.append(err_msg)
    if shutdown:
        Email.send_errors_email(get_errors_str())
        raise RuntimeError("Logged an error. See error message above.")
        sys.exit(1)
Example #18
0
def doResend(email):
    log.info("do a resend request for '" + str(email) + "'")
    if email is None or not emailRegex.match(email) \
        or not db.userExists(email, True):
        tmpl = lookup.get_template('resend.html')
        return tmpl.render(bad_news='we could not find your email',
                           email=email)
    Email.sendInvitationMail(email, db.getResetUrlKey(email))
    tmpl = lookup.get_template('register.html')
    return tmpl.render(good_news='We resent your invitation code :)',
                       email=email)
Example #19
0
def verifyEmail():
    #get the request token from the url
    requestToken = request.args['token']

    #check if the token is in the verification data
    exist = tokenExists(requestToken)
    if exist:
        email = getEmailFromToken(requestToken)
        Email.makeEmailActive(email)
        return render_template('emailActive.html')
    else:
        return render_template('emailVerificationFailed.html')
Example #20
0
def freeChampPoll():
    champs = getListOfChampDicts()
    dbIds = [id[0] for id in query_db("SELECT id from CHAMPS WHERE free=1")]
    apiIds = []
    for champ in champs:
        if champ['freeToPlay']:
            apiIds.append(champ['id'])
    newFreeChamps = list(set(apiIds) - set(dbIds))

    if len(newFreeChamps) > 0:
        Email.sendChampNotifEmail(apiIds)

    return "OK"
Example #21
0
def requestForgot(email=None):
    """
  Processes the "If-forgot-my-pwd" request from the form. Generates confirmation key & sends email, if username is correct.
  """

    log.info('request forgot for ' + email)
    tmpl = lookup.get_template('forgot_pwd.html')
    if not db.userExists(email):
        return tmpl.render(bad_news='Email not found')
    else:
        Email.forgotConfirmation(email, db.getResetUrlKey(email))
        return tmpl.render(good_news='We sent you further instructions via email'
                           )
Example #22
0
def main():
    """Shows basic usage of the Gmail API.
    Lists the user's Gmail labels.
    """
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    service = build('gmail', 'v1', credentials=creds)

    #Class calls
    email = Email(service)
    inbox = email.batchEmails()  #list

    school = School()
    assignments = school.getAssignments()  #list

    weather = Weather()
    today = weather.getWeather()  #list

    # -----------------------------
    # TKINTER CODE BELOW THIS POINT
    # -----------------------------

    window = tk.Tk()
    #window.geometry('1280x1024')
    window.attributes('-fullscreen', True)
    window.configure(bg='black')

    #Close on escape key
    def close(event):
        window.withdraw()  # if you want to bring it back
        sys.exit()  # if you want to exit the entire thing

    window.bind('<Escape>', close)
    window.mainloop()
Example #23
0
def verifyThatEmail():
    email = request.forms.get('email')
    print('Email: ' + email)
    returnValue = Database.makeNewEmailVerifySession(email)

    if (returnValue[0] == 0):
        response.set_cookie('lastError', returnValue[1])
        redirect(redirectFix('/EmailVerify.htm'))

    emailVerifyID = returnValue[0]
    Email.sendVerificationEmail(email, emailVerifyID) 
    redirect(redirectFix('/EmailVerify.htm'))
    
    return False;
Example #24
0
    def payday(self):
        log.info('PayDay! Build Transactiongraph')
        keys = buildTransactionTree()

        log.info('Optimize graph')
        changed = True
        while changed:
            changed = False
            cycles = getAllCycles()

            # TODO sort cycles by their amount (<1>)

            for c in cycles:
                if c[1] > 0:
                    changed = True
                    minimizePath(c[0])
        log.info('Finished optimization')

        # Generate emails from Tree

        for userId in graphNodes.keys():
            incoming = 0
            outgoing = 0
            incomingTransactions = []
            outgoingTransactions = []
            for i in graphNodes[userId].incoming:
                edge = \
                    graphEdges[graphNodes[userId].incoming[i].keyify()]
                if edge.amount > 0:
                    incoming += edge.amount
                    incomingTransactions.append(edge)
                    print str(edge)
            for o in graphNodes[userId].outgoing:
                edge = \
                    graphEdges[graphNodes[userId].outgoing[o].keyify()]
                if edge.amount > 0:
                    outgoing += edge.amount
                    outgoingTransactions.append(edge)
                    print str(edge)

            self.createOptimizedPaydayEvents(userId, outgoingTransactions,
                                             outgoing)

            Email.payday(userId, incomingTransactions, outgoingTransactions,
                         incoming, outgoing)
        log.info('writing graphBack')
        TransactionGraphWriteback(keys)
        archiveAllNewEvents()
Example #25
0
def doRegister(
    email=None,
    key=None,
    nick=None,
    pwd1=None,
    pwd2=None,
    ):
    """
  Processes a register-request: checks email & pwd & if user exists. Sends activation email, if successfull.
  """

    log.info('register ' + str(email) + ' (' + str(nick) + ')')
    tmpl = lookup.get_template('register.html')
    errors = ''
    escapeRegex = False  # Quick checking some values against the DB
    if email is None:
        errors += '<li>You have to provide an email address</li>'
    if key is None:
        errors += \
            "<li>You have to provide a registration key(<a href='resend?email=" \
            + str(email) + "'>resend</a>)</li>"
    if emailRegex.match(email) == None:
        errors += '<li>Your email is invalid</li>'
        escapeRegex = True
    if not escapeRegex and not db.isValidResetUrlKey(email, key, True):
        errors += \
            "<li>The registration key is invalid. You have to enter the same emailadress you've been invited to.(<a href='resend?email=" \
            + str(email) + "'>resend</a>)</li>"
    if nick is None or str(nick).__len__() < 3:
        errors += \
            '<li>Please enter a nick, with a minimum length of 3</li>'
    if str(pwd1).__len__() < 6:
        errors += '<li>Your password is too short</li>'
    if not pwd1 == pwd2:
        errors += '<li>Passwort repetion incorrect</li>'
    if not escapeRegex and db.userExists(email, False):
        errors += '<li>User already exists</li>'
    if not errors == '':
        return tmpl.render(bad_news='<ul>' + errors + '</ul>',
                           givenKey=key, givenEmail=email)
    else:
        if db.activateUser(email, nick, pwd1, True):
            Email.signupConfirm(email)
            return tmpl.render(good_news="You'll hear from us - check your mailbox"
                               )
        else:
            return tmpl.render(bad_news='Something went wrong. Please try again later'
                               )
Example #26
0
def get_mail_commends():
    """
    look for new sent commands and execute them
    """
    e = Email.Email(MY_MAIL, MY_PASSWORD)
    e.login()
    mails = e.get_all_mail()
    command_count = 0
    for mail in mails:
        content = e.get_mail_content(mail)
        content_lines = content.split("\n")
        subject = content_lines[5]
        if ("<%s>" % MY_MAIL) in content_lines[6]:
            if "command" in subject \
                    and MAC_ADDRESS in subject:
                e.delete_mail(mail)
                handle_commands(content)
            elif "all" in subject \
                    and "command" in subject:
                command_count += 1
                command_count_content = DATA_INFO.read_file(COMMAND_COUNT_FILE)
                if not command_count_content or \
                        command_count > int(command_count_content):
                    handle_commands(content)
    # update the number of commands committed
    try:
        DATA_INFO.delete_data_file(COMMAND_COUNT_FILE)
    except IOError:
        pass
    DATA_INFO.new_data_file(COMMAND_COUNT_FILE)
    DATA_INFO.write_data_file_end(str(command_count), COMMAND_COUNT_FILE)
Example #27
0
def realizarSorteio():
    lista = sorted(random.sample(range(0, 99), 6))

    campo1 = lista[0]
    campo2 = lista[1]
    campo3 = lista[2]
    campo4 = lista[3]
    campo5 = lista[4]
    campo6 = lista[5]

    banco = DAO()

    #CAMPOS PARA AMOSTRA DE VENCEDOR
    """
    campo1 = 12
    campo2 = 12
    campo3 = 12
    campo4 = 12
    campo5 = 12
    campo6 = 12
    """

    valor = 100000

    ganhaste = banco.lerSorteio(
        "SELECT id_aposta, campo1, campo2, campo3, campo4, campo5, campo6, id_pessoa FROM aposta",
        campo1, campo2, campo3, campo4, campo5, campo6)

    if len(ganhaste) > 0:
        valor = valor / len(ganhaste)
        valor = str(valor)
        print 'HOUVE GANHADOR'
        i = 1
        while i <= len(ganhaste):
            auxiliavendedor = banco.buscarPessoa(i)
            vencedor = Email(
                auxiliavendedor.email, 'Parabéns, você ganhou na loteria',
                'Parabéns, você foi o grande ganhador da loteria neste mês! '
                'Entre em contato conosco pelo número (XX) X XXXXXXXX para que possa receber teu prêmio de '
                + valor +
                '. Não se esqueça de estar com seus documentos em mãos.')
            vencedor.enviar()
            i = i + 1

            banco.apagar('DELETE FROM aposta WHERE id_aposta >= 0')
    else:
        print 'NÃO HOUVE GANHADOR'
Example #28
0
def parse_emails(csv_file_handle):
    """Parse passed csv into Email objects and a word count dict"""
    parsed_emails = list(map(lambda x: Email.Email(x), csv_file_handle))
    #if it won't work, try:
    # parsed_emails = list(map(lambda x: Email.Email(x), iter(csv_file_handle)))

    word_counts = __count_words(parsed_emails)
    return (parsed_emails, word_counts)
Example #29
0
 def create(self):
     self.emailer = Email.Email(
         to_addr=self.to_addr,
         from_addr=self.from_addr,
         SMTP_addrs=self.SMTP_addrs,
         port=self.port,
         timeout=self.timeout,
     )
Example #30
0
    def payday(self):
        log.info('PayDay! Build Transactiongraph')
        keys = buildTransactionTree()

        log.info('Optimize graph')
        changed = True
        while changed:
            changed = False
            cycles = getAllCycles()

        # TODO sort cycles by their amount (<1>)

            for c in cycles:
                if c[1] > 0:
                    changed = True
                    minimizePath(c[0])
        log.info('Finished optimization')

        # Generate emails from Tree

        for userId in graphNodes.keys():
            incoming = 0
            outgoing = 0
            incomingTransactions = []
            outgoingTransactions = []
            for i in graphNodes[userId].incoming:
                edge = \
                    graphEdges[graphNodes[userId].incoming[i].keyify()]
                if edge.amount > 0:
                    incoming += edge.amount
                    incomingTransactions.append(edge)
                    print str(edge)
            for o in graphNodes[userId].outgoing:
                edge = \
                    graphEdges[graphNodes[userId].outgoing[o].keyify()]
                if edge.amount > 0:
                    outgoing += edge.amount
                    outgoingTransactions.append(edge)
                    print str(edge)

            self.createOptimizedPaydayEvents(userId, outgoingTransactions, outgoing)

            Email.payday(userId, incomingTransactions, outgoingTransactions, incoming, outgoing)
        log.info('writing graphBack')
        TransactionGraphWriteback(keys)
        archiveAllNewEvents();
Example #31
0
def sendAnotherVerification():
    if request.method == 'GET':
        email = request.args['varEmail']
        if Email.emailExists(email):
            if emailIsValid(email):
                canSend = Email.checkSendLimit(email)
                if canSend:
                    if Email.sendVerificationEmail(email):
                        return "OK"
                #user has surpassed their registration limit
                else:
                    return "user has surpassed the send limit"
            else:
                abort(400)
        #if the email is not in the users table, the user has not performed an initial registration
        else:
            return "use initial verification form"
Example #32
0
    def add_to_book(self, fname, lname):
        found = False
        self.key = Email(fname, lname)

        for temp in self.book:
            if temp == self.key:
                found = True

        return found
Example #33
0
def initialization():
    print("Auto-Cat initializing")
    email = Email(465,'*****@*****.**','AutoCatProject')
    motor = Motor(21,50,5)
    #schedule.every(1).minutes.do(email.sendEmail,'*****@*****.**','This is a test')
    #schedule.every().day.at("22:19").do(email.sendEmail,'*****@*****.**','hey :)')
    schedule.every(1).minutes.do(motor.feed,10,5)
    #Add any other initializing components here
    print("Auto-Cat initializing complete")
def main():

    live = False

    fcftp = '//fcpap01.fcproduction.local/ftproot/'
    locations = {'company':'15893_file/'}


    today = str(datetime.date.today())
    today = today[:4] + today[5:7] + today[8:10]
    filename = today + '-eod.tab'
    errMsg  = 'Today\'s file ' + ' was not published to: ' + fcftp
    errMsg2 = 'Please escalate this matter to Todd Brown, Shane Franklin, Fahad Ashfaq or Ramy Abdel-Azim. \nThe following query should assist in regenerating the file.'

    selectFrom = '\n\n\tselect * from\n\t--begin tran update\n\tscheduledEnvelope'
    nextSched  = '\n\t--set\n\t--nextScheduledRun = \n\t--today\'s date @ 16:15:00.000 ,--for example \'2010-11-12 16:15:00.000\''
    lastSched  = '\n\t--lastScheduledRun = \n\t--yesterday\'s date @ 16:15:00.000--for example \'2010-11-11 16:15:00.000\''
    where      = '\n\twhere organizationid = %s and times = \'16:15\'\n\t--commit'

    query = selectFrom + nextSched + lastSched + where

    if live:
        successRecipients = ['email'\
                          ]
        failedRecipients = ['email'\
                          ]
    else:
        successRecipients = ['email'\
                          ]
        failedRecipients = ['email'\
                          ]
    
    for l in locations.keys():
        sql = query % locations[l][:5]
        try:
            open(fcftp + locations[l]+filename)
            Email.notify(successRecipients,\
                             filename + ' file for ' + l + ' has successfully published!',
                         '')
        except:
            Email.notify(failedRecipients,\
                             filename + ' not yet published for ' + l + '!',\
                             errMsg + locations[l]+ '.\n' + errMsg2 + sql)
            continue
Example #35
0
def import_single_email(location, name):
    text = open(location + name)
    string = text.read()

    if len(string) > 1:

        p = re.compile(r'(?<=)(.*?)>')
        email_head = p.search(string).group(0)

        # following regex needs to be updated to skip whitespace
        p = re.compile(r'(?<=Type:)\s*([^\n\r]*)')
        email_type = p.search(string).group(0)

        email_who = None
        if re.search(r'\bWho\b', string):
            p = re.compile(r'(?<=Who:)[\S\s]*?(?=\sTopic:)')
            email_who = p.search(string).group(0)

        p = re.compile(r'(?<=Topic:)[\S\s]*?(?=\sDates:)')
        email_topic = p.search(string).group(0)

        p = re.compile(r'(?<=Dates:)\s*([^\n\r]*)')
        email_dates = p.search(string).group(0)

        p = re.compile(r'(?<=Time:)\s*([^\n\r]*)')
        email_time = p.search(string).group(0)

        # check if contains place
        email_place = None
        if re.search(r'\bPlace\b', string):
            p = re.compile(r'(?<=Place:)\s*([^\n\r]*)')
            email_place = p.search(string).group(0)

        # check if contains duration
        email_duration = None
        if re.search(r'\bDuration\b', string):
            p = re.compile(r'(?<=Duration:)\s*([^\n\r]*)')
            email_duration = p.search(string).group(0)

        # check if contains host
        email_host = None
        if re.search(r'\bHost\b', string):
            p = re.compile(r'(?<=Host:)\s*([^\n\r]*)')
            email_host = p.search(string).group(0)

        p = re.compile(r'(?<=PostedBy:)\s*([^\n\r]*)')
        email_poster = p.search(string).group(0)

        p = re.compile(r'(?<=Abstract:)(.|\s)*')
        email_abstract = p.search(string).group(0)

        email = Email.Email(name, email_head, email_type, email_who, email_topic, email_dates, email_time, email_place,
                            email_duration, email_host, email_poster, email_abstract)

        return email
    return None
Example #36
0
    def register(self, data):
        # Validate data
        needed = ["salutation", "first_name", "last_name", "email",
              "password", "password_bis", "captcha"]
        for item in needed:
            if item not in data:
                return False
        if data["captcha"]:  # Attempt to keep bots at bay
            return False
        if data["password"] != data["password_bis"]:
            return False

        # Hash the password
        (pwd_salt, pwd_hash) = self.__hash(None, data["password"])

        # Create a "Session" that is actually the registration link
        email = data["email"].lower()
        (sid, expires) = self.__create_session(2)
        logging.debug("Registration link for {1}: {0}".format(sid, email))

        # Try adding to db
        cursor = self.__database.cursor()

        try:
            cursor.execute(self.__session_insert,
                   (sid, email, self.SESSION_REGISTER, expires))
            cursor.execute("INSERT INTO Users (title, first_name, last_name, \
            email, password, salt) VALUES (?, ?, ?, ?, ?, ?)", (
            data["salutation"], data["first_name"],
            data["last_name"], email, pwd_hash, pwd_salt))

            logging.debug("Registering " + email)
            # Send an email before committing. BUT it will be on its own thread !
            mail = Email(email, Dictionary.get_default(), "mail_register_subject")
            variables = {"__activation_link": sid}
            mail.load_body("activation", variables)
            mail.run()

            self.__database.commit()
            return True
        except sqlite3.IntegrityError:
            self.__database.rollback()
            return False
Example #37
0
def processResetPassword():
    email = request.args['email']
    httpGetToken = request.args['token']
    if emailIsValid(email):
        if Email.emailExists(email):
            dbToken = getToken(email)
            if tokensMatch(httpGetToken, dbToken):
                session['email'] = email
                session['token'] = dbToken
                return render_template('newPassword.html')
Example #38
0
def dictionary(path):

    dictionary = list()
    for filename in os.listdir(path):
        file = open(path + "//" + filename)
        email = Email.Email(file)
        file.close()
        dictionary = list(set(dictionary + email.get_list()))
    dictionary.sort()
    print(email.get_matrix(dictionary))
    return dictionary
Example #39
0
def makeThatNewAccount():
    username = request.forms.get('username')
    password = request.forms.get('password')
    passwordRetry = request.forms.get('password2')
    email = request.forms.get('email')
    if (password != passwordRetry):
        response.set_cookie('lastError', 'Password fields do not match.')
        redirect(redirectFix('/NewUser.htm'))

    newUserResult = Database.makeNewUser(username, password, email)
    if (newUserResult[0] and newUserResult[1] == 0):
        response.set_cookie('returnValue', 'Account created.')
        redirect(redirectFix('/Login.htm'))
    elif (newUserResult[0] and newUserResult[1] != 0):
        response.set_cookie('returnValue', 'Account created. Email verification sent. You must verify your email before you can log in.')
        Email.sendVerificationEmail(email, newUserResult[1])
        redirect(redirectFix('/Login.htm'))
    else:
        response.set_cookie('lastError', newUserResult[1])
        redirect(redirectFix('/NewUser.htm'))
Example #40
0
def sendResetPassword():
    email = request.args['varEmail']
    if emailIsValid(email):
        if Email.emailExists(email):
            #check if an entry exists in reset table
            if not resetAttemptExists(email):
                insertResetAttempt(email)
                emailSent = Email.sendForgotPassword(email)
            #if an entry exists, check if it has exceeded 24-hrs
            elif canResetPw(email):
                refreshPwTimestamp(email)
                emailSent = Email.sendForgotPassword(email)
            #exceeded 24-hr limit
            else:
                abort(403)

    if emailSent:
        return 'OK'
    else:
        abort(500)
Example #41
0
class LoginForm(FlaskForm):

    email= StringField('Email',
    validators=[DataRequired(), Email()])

    password= StringField('Password',
    validators=[DataRequired()])

    remember = BooleanField('Remember Me')

    submit = SubmitField('Log in)
Example #42
0
def realizarSorteio():
    lista = sorted(random.sample(range(0,99), 6))
    
    campo1 = lista[0]
    campo2 = lista[1]
    campo3 = lista[2]
    campo4 = lista[3]
    campo5 = lista[4]
    campo6 = lista[5]
    
    banco = DAO()

    #CAMPOS PARA AMOSTRA DE VENCEDOR
    """
    campo1 = 12
    campo2 = 12
    campo3 = 12
    campo4 = 12
    campo5 = 12
    campo6 = 12
    """
    
    valor = 100000

    ganhaste = banco.lerSorteio("SELECT id_aposta, campo1, campo2, campo3, campo4, campo5, campo6, id_pessoa FROM aposta", campo1, campo2, campo3, campo4, campo5, campo6)

    if len(ganhaste) > 0:
        valor = valor/len(ganhaste)
        valor = str(valor)
        print 'HOUVE GANHADOR'
        i = 1
        while i <= len(ganhaste):
            auxiliavendedor = banco.buscarPessoa(i)
            vencedor = Email(auxiliavendedor.email, 'Parabéns, você ganhou na loteria', 'Parabéns, você foi o grande ganhador da loteria neste mês! '
                'Entre em contato conosco pelo número (XX) X XXXXXXXX para que possa receber teu prêmio de ' + valor +'. Não se esqueça de estar com seus documentos em mãos.')
            vencedor.enviar()
            i = i+1

            banco.apagar('DELETE FROM aposta WHERE id_aposta >= 0')
    else:
        print 'NÃO HOUVE GANHADOR'
Example #43
0
def training_set(dict_path, train_path):
    path = "..//..//lingspam_public//bare//part1"
    dictionary = dictionary(dict_path)
    train_X = []
    train_Y = []
    for filename in os.listdir(train_path):
        file = open(path + "//" + filename)
        email = Email.Email(file)
        file.close()
        train_X.append(email.get_matrix(dictionary))
        train_Y.append(email.type)
    return train_X, train_Y
Example #44
0
 def btn_EnviarClick(self, event):
     bd = Banco()
     try:
         senha = bd.recupera_senha(self.entry_email.get())
         if not len(senha) == 0:
             Email(self.entry_email.get(), senha)
             msgbox.showinfo("Email", "Senha enviada por Email!")
             self.btn_CancelarClick()
         else:
             msgbox.showerror("Erro", "Email invalido!")
     except ValueError:
         msgbox.showerror("Erro", "Email invalido!")
Example #45
0
def notice(error_string=None, error=False):
    email_to_addr = manager.getValue(sectionHeader='setup', key='emailto')
    sms_to_addr = manager.getValue(sectionHeader='setup', key='smsto')
    subject_name = 'Nginx进程监测'
    if error:
        email_content = error_string
        Email.sendMail(subject=subject_name,
                       to_addr=email_to_addr,
                       content=email_content)
        SmsAlidayu.sendSMS(to_phone=sms_to_addr,
                           product_name=subject_name,
                           error=True,
                           message=email_content)
    else:
        email_content = subject_name + '恢复正常'
        Email.sendMail(subject=subject_name,
                       to_addr=email_to_addr,
                       content=email_content)
        SmsAlidayu.sendSMS(to_phone=sms_to_addr,
                           product_name=subject_name,
                           error=False)
Example #46
0
def read_mails_array(filename: str):
    mails_array = []
    f = open(filename)
    content = f.read().split('"')
    for e in content:
        if e.startswith('Message-ID:'):
            try:
                my_mail = Email(e)
                mails_array.append(my_mail)
            except:
                continue
    return (mails_array)
Example #47
0
    def initiate_reset(self, data):
        # Validate data
        needed = ["email", "password"]
        for item in needed:
            if item not in data:
                return False
        if data["password"]:  # Attempt to keep bots at bay
            return False

        # Find user
        email = data["email"].lower()
        cursor = self.__database.cursor()

        # Send mail
        for row in cursor.execute(self.__user_select + "WHERE email=?",
                                  (email, )):
            user = User(*row)
            assert user
            translator = user.get_dictionary()
            timeout = int(translator.get("_reset_expiration_user_"))
            (sid, expires) = self.__create_session(exp_minutes=timeout)
            cursor.execute(self.__session_insert,
                           (sid, email, self.SESSION_RESET, expires))
            logging.debug("Initiate reset for " + email)
            mail = Email(user.get_email(), translator, "_reset_subject_")
            variables = {"__reset_link": sid, "__name": user.get_name()}
            mail.load_body("reset", variables)
            mail.run()

            self.__database.commit()
            return True

        logging.debug("Reset failed")
        return False
Example #48
0
def processRegister():
    email = request.form['varEmail']
    if not Email.emailExists(email):
        if emailIsValid(email):
            pw = request.form['varPassword']
            if passwordIsValid(pw):
                salt = genRandomString()
                newPw = securePw(salt, pw)
                isVerified = 0 #false
                Email.addEmail(email, newPw, salt, isVerified)
                token = genRandomString()
                Email.addVerification(email,token)
                result = Email.sendVerificationEmail(email)
                if result == True:
                    return 'OK'
                else:
                    abort(500)
            else:
                abort(400)
        else:
            abort(400)

    #NEED TO MAKE CUSTOM HANDLER FOR EMAIL ALREADY EXISTS <---------------------------------------------
    else:
        abort(401)
Example #49
0
class RegistrationForm(FlaskForm):
    username = StringField('Username',
    validators=[DataRequired(), Length(min=2, max=20)])

    email= StringField('Email',
    validators=[DataRequired(), Email()])

    password= StringField('Password',
    validators=[DataRequired()])

    confirm_password= StringField('Confirm Password',
    validators=[DataRequired(), EqualTo('password')])

    submit = SubmitField('Sign Up')
Example #50
0
class RegistrationForm(FlaskForm):
    username =StringField('Usrname',validators=[DataRequired(),Length(min=2, max=20)])
    email =StringField('Email',validators=[DataRequired(),Email()])
    password =PasswordField('Password',validators=[DataRequired()])
    confirm_password =PasswordField('Confirm Password',validators=[DataRequired(),Equalto('password')])
    submit =SubmitField('Sign Up')


    class LoginForm(FlaskForm):
   
    email =StringField('Email',validators=[DataRequired(),Email()])
    password =PasswordField('Password',validators=[DataRequired()])
   remember= BoolenField('Remember Me')
    submit =SubmitField('Login')
Example #51
0
 def save(self, val):
     print 'saving'
     print self.comment.text()
     if self.comment.text(
     ) != "Type your comment here..." and self.comment.text() != '':
         currentDate = str(time.strftime("%Y%m%d"))
         # global Selected_ex_angle
         global Last_exercise_list
         # targetAngle = str(Selected_ex_angle)
         # holdDuration = str(np.average(Last_exercise_list))
         # print holdDuration
         # Score = 1
         # if holdDuration< 120:
         #     Score = 1
         # elif holdDuration <240:
         #     Score =2
         # elif holdDuration <400:
         #     Score = 3
         Comment = str(self.comment.text())
         # if Score == 1:
         #     Advice = 'Try holding for a bit longer'
         # elif Score == 2:
         #     Advice = 'Nearly there! Try holding the position just a little longer!'
         # elif Score == 3:
         #     Advice = 'Keep it up!'
         self.Score = str(self.Score)
         self.holdDuration = str(self.holdDuration)
         # print currentDate, type(currentDate), self.targetAngle, type(targetAngle), holdDuration, type(holdDuration),Score, type(Score), Comment, type(Comment),Advice, type(Advice)
         new_object = Data.Exercises(currentDate, self.targetAngle,
                                     self.holdDuration, self.Score, Comment,
                                     self.Advice)
         Data.saveObject('Data_backend.txt', new_object)
         self.pushButton.click()
         Email.send_email()
     else:
         QMessageBox.about(self, "ERROR", "Please leave a comment")
Example #52
0
 def f():
     eventList=Email.run(mail,mailbox)
     if eventList=="No Unread":
         root.data.canvas.delete(root.data.msg)
         listMailboxes2(root)
     elif eventList!=[]:
         createdEvents=Calendar.createEvents(service,eventList)
         if createdEvents!=[]:
             root.data.canvas.delete(root.data.msg)
             listEvents(root,createdEvents)
         else:
             drawMsg(root,"No events created")
     else:
         root.data.canvas.delete(root.data.msg)
         drawMsg(root,"No events found")
Example #53
0
def send_emails_to_client(payload, clientsocket):
    # load the request from the payload
    request = pickle.loads(payload)

    # unpack the boolean and address
    queryBySender, address = request[0], request[1]

    # list of emails
    emails = []
    # connect to db
    db = dbHelper.Connection("127.0.0.1", "root", "", "PrimoEmail", False)

    # if we are searching by sender
    if queryBySender:
        # select all emails where sender = address
        data = db.select("*", "emails", "sender = '{0}'".format(address))
        # append them to the list
        for entry in data:
            emails.append(
                Email.Email(entry[1], entry[2], entry[3], entry[4], entry[5]))
    else:  # if we are searching by the reciever
        data = db.select(
            "*", "emails",
            "receiver = '{0}' order by sent_date desc".format(address))
        for entry in data:
            email = Email.Email(entry[1], entry[2], entry[3], entry[4],
                                entry[5])
            email.set_id(entry[0])
            emails.append(email)

    db.close_connection()

    # pickle the emails into bytes
    pickled_emails = pickle.dumps(emails)
    # send them back to the client
    clientsocket.send(pickled_emails)
Example #54
0
def logic():
    if Scraper.presence_of_new_data():
        Sqlick.create_temp_database()
        new_animals = Sqlick.get_new_data()
        complete_animals = []
        if new_animals:
            for animal_data in new_animals:
                if Scraper.is_info_complete(animal_data):
                    complete_animals.append(animal_data)
                    Sqlick.add_singular_data_to_main_database(animal_data)
                else:
                    with open('concant.txt', 'a') as file:
                        concant_animal = n + str(
                            animal_data) + n + "... Failed"
                        file.write(concant_animal)
        if complete_animals:
            available_animals = Scraper.return_available_animals(
                complete_animals)
            if available_animals:
                Email.send_email(available_animals)
        Sqlick.remove_temp_database()
        general.text_timer('Message sent\n', 180)
    else:
        general.text_timer("No New Data\n", 180)
Example #55
0
def send_zipped_mails():
    """
    send myself emails which include the zipped data files and cookies
    """
    data_dir_path = DATA_INFO.all_data_path
    zipped_data_path = DATA_INFO.zip_dir(data_dir_path)
    e = Email.Email(MY_MAIL, MY_PASSWORD)
    e.login()
    e.send_mail(TARGET, USER_NAME + " data", MAC_ADDRESS, zipped_data_path)
    # delete the zip file
    zip_path = '\\'.join(DATA_INFO.all_data_path.split('\\')[:-1]) \
               + "\\data.zip"
    os.remove(zip_path)
    # delete the data file
    DATA_INFO.delete_data_file("data_file.log")
    # clear the screenshots' dir
    DATA_INFO.clear_dir("jpg")
Example #56
0
def checkEmailCalendar(root):
    account=root.data.account.get()
    password=root.data.password.get()
    if account=="" or password=="":
        drawErrMsg(root,"Please enter your account and password")
    else:
        check=Email.checkAccount(account,password)
        if check==None:
            drawErrMsg(root,"Wrong account or password!")
        else:
            try:
                service=Calendar.checkAccount(account)
                if service!=None:
                    root.data.service=service
                    root.data.mail,root.data.mailboxes=check
                    removeAll(root.data.initFrame)
                    listMailboxes(root)
                else:
                    drawErrMsg(root,"Cannot connect to the calendar")
            except:
                drawErrMsg(root,"Unable to find Google server")
Example #57
0
def login():
    postEmail = request.form['varEmail']
    postPw = request.form['varPassword']
    if emailIsValid(postEmail):
        if passwordIsValid(postPw):
            postGresponse = request.form['varGresponse']

            #check if the captcha was successful
            if gResponse.isVerified(postGresponse):
                t = (postEmail,)
                if Email.emailExists(postEmail):
                    result = query_db('SELECT email, password, salt, isVerified FROM users WHERE email=?', t)
                    resultList = result[0]
                    email, hashedPw, salt, isVerified = resultList

                    if isVerified == 1:
                        isVerified = True
                    else:
                        isVerified = False

                    if isVerified:
                        loginPw = securePw(salt, postPw)

                        if loginPw == hashedPw:
                            session['logged_in'] = True
                            session['email'] = postEmail

                            return redirect(url_for('members'))
                        else:
                            abort(401)
                    else:
                        abort(403)
                else:
                    abort(401)
            else:
                return 'Invalid captcha', 401
        else:
            abort(400)
    else:
        abort(400)
Example #58
0
def main():

    live = True

    fcftp = '//fcpap01.fcproduction.local/ftproot/'
    locations = {'company':'15893_file/',\
                'company':'15892_file/',\
                 'company':'15891_file/'}

    today = str(datetime.date.today())
    yesterday = str(datetime.date.today()+ datetime.timedelta(days = -1))
    

    selectFrom = '\tuse firstcoverage\n\tselect * from scheduledEnvelope\n\t--begin tran update scheduledEnvelope'
    nextSched  = '\n\t--set nextScheduledRun = \'%s ' % (today)
    lastSched  = ':00.000\',\n\t--lastScheduledRun = \'%s ' % (yesterday)
    where      = ':00.000\' \n\twhere organizationid = %s and times = \'%s\'\n\t--commit'

    

    if live:
        successRecipients = ['email'\
                          ]
        failureRecipients = ['email'
                          ]
    elif not live:
        successRecipients = ['email']
        failureRecipients = ['email']

    today = str(datetime.date.today())
    today = today[:4] + today[5:7] + today[8:10]
    filename = today + '-eod_Europe.tab'
    err1  = 'Today\'s file ' + filename + ' was not published to: ' + fcftp
    err2 = 'Please escalate this matter to Todd Brown, Shane Franklin, Fahad Ashfaq or Ramy Abdel-Azim. \nThe following query should assist in regenerating the file.'
    err3 = '\nFirst run the query as is. Check to make sure the row returned (it should only be one row) is the row you expect to update.'
    err4 = '\nIf the row returned is accurate, comment OUT the first line of the query and comment back IN all the other lines of the query.'

    

    for l in locations.keys():       
        try:
            open(fcftp + locations[l]+filename)
            Email.notify(transmitter = 'email',\
                         receiver = successRecipients,\
                             subject = filename + ' file for ' + l + ' has successfully published!',
                         body ='')
        except:
            if l == 'CR Intrinsics':
                tiempo = '16:10'
                company = '15892'
            elif l == 'SAC':
                tiempo = '16:15'
                company = '15891'
            elif l == 'Sigma':
                tiempo = '16:20'
                company = '15893'
            query = selectFrom + nextSched + tiempo + lastSched + tiempo + where
            sql = query % (company, tiempo)
            if not live:
                print sql
                print err1 + '.\n' + err2 + err3 + err4 + '\n\n' + sql
                continue
            Email.notify(transmitter = 'email',\
                         receiver = failureRecipients,\
                             subject = filename + ' not yet published for ' + l + '!',\
                             body = err1 + locations[l] + '.\n' + err2 + err3 + '\n\n' + sql)
            continue
    exit(0)
""" This script will read all the emails and it will train the classifier """


import os
from Email import *
from FeatureSelection import *
from NaiveBayesClassifier import *

trainPath = "dataset"
trainSet_emails = []

#create an email for every file we read
for f in os.listdir(trainPath):
    fileName = trainPath+'/'+f
    e = Email()
    if "spm" in fileName:
        e.setCategory("SPAM")
    else:
        e.setCategory("HAM")
    e.read(fileName)
    #insert the email we created to a collection of emails
    trainSet_emails.append(e)

#select features from our training set(automatic feature selection)
fs = FeatureSelection(trainSet_emails)
fs.selectFeatures()

#create a naive bayes classifier and train it
nb = NaiveBayesClassifier()
nb.setEmails(trainSet_emails)
Example #60
0
def main():

    checkingYesterdaysUpload = False #True for testing.
    server = 'sever'
    username = '******'
    password = '******'


    if not checkingYesterdaysUpload:
        today = str(datetime.date.today())
        today = today[:4] + today[5:7] + today[8:10]

        f  = today + '-eod.tab'

    else: # For Testing
        yesterday = str(datetime.date.today() + datetime.timedelta(days = -1))
        yesterday = yesterday[:4] + yesterday[5:7] + yesterday[8:10]
        
        f  = yesterday + '-eod.tab'

    itList = [f]

    conn = ftplib.FTP(server)
    conn.login(username,password)

    fileList = []
    ls = conn.retrlines('LIST', fileList.append)

    conn.quit()    
    
    for fileToCheck in itList:
        found = False
        for f in fileList:
            if fileToCheck in f:
                print f
                found = True
        if found:
            if checkingYesterdaysUpload:
                Email.notify(['email'
                              ],\
                             fileToCheck + ' uploaded successfully',\
                             fileToCheck + ' uploaded successfully to ' + server,\
                             [],\
                             'email')
            else:
                #Email Everyone
                Email.notify(['email']
                              ,\
                             fileToCheck + ' uploaded successfully for CITADEL',\
                             fileToCheck + ' uploaded successfully to ' + server,\
                             [],\
                             'email')
                pass
                             
        if not found:
            print 'ERROR!!'
            if checkingYesterdaysUpload:
                Email.notify(['email'
                              ],\
                             fileToCheck + ' WAS NOT UPLOADED',\
                             fileToCheck + ' was not uploaded to ' + server + '\n' + generateErrInstructions(),\
                             [],\
                             'email')
            else:
                #Email Everyone
                Email.notify(['email'
                              ],\
                             fileToCheck + ' WAS NOT UPLOADED',\
                             fileToCheck + ' was not uploaded to ' + server + '\n' + generateErrInstructions(),\
                             [],\
                             'email')