def send_status_mail(self, server_id, event, message):
     # Get server entry and find configured e-mail
     servers = self._status_serverDb.get_server({"id": server_id},
                                                detail=True)
     if not servers:
         msg = "No server found with server_id " + server_id
         self._smgr_log.log(self._smgr_log.ERROR, msg)
         return -1
     server = servers[0]
     email_to = []
     if 'email' in server and server['email']:
         email_to = self.get_email_list(server['email'])
     else:
         # Get cluster entry to find configured e-mail
         if 'cluster_id' in server and server['cluster_id']:
             cluster_id = server['cluster_id']
             cluster = self._status_serverDb.get_cluster({"id": cluster_id},
                                                         detail=True)
             if cluster and 'email' in cluster[0] and cluster[0]['email']:
                 email_to = self.get_email_list(cluster[0]['email'])
             else:
                 self._smgr_log.log(
                     self._smgr_log.DEBUG,
                     "cluster or server doesn't configured for email")
                 return 0
         else:
             self._smgr_log.log(self._smgr_log.DEBUG,
                                "server not associated with a cluster")
             return 0
     send_mail(event, message, '', email_to,
               self._status_thread_config['listen_ip'], '25')
     msg = "An email is sent to " + ','.join(
         email_to) + " with content " + message
     self._smgr_log.log(self._smgr_log.DEBUG, msg)
def home():
    if request.method == 'POST':
        url = request.form.get('URL')
        sender_email = request.form.get('Email')
        desired_price = request.form.get('Desired_price')
        page1 = requests.get(url).text
        soup = BeautifulSoup(page1, 'lxml')

        product_name = soup.find('h1').text.strip()
        page = requests.get(url)

        soup = BeautifulSoup(page.content, 'html.parser')

        price = soup.find("div", {"class": "_3qQ9m1"}).text
        price = price[1:]

        price_ar = price.split(",")
        price = ''.join(price_ar)

        price = int(price)
        desired_price = int(desired_price)

        if desired_price >= price:
            send_mail()

        return render_template("flask_weather_app.html",
                               price=price,
                               product_name=product_name)
    return render_template("flask_weather_app.html")
Exemplo n.º 3
0
def add_candidat():
    nom = request.form['nom']
    prenom = request.form['prenom']
    email = request.form['email']
    dateNaissance = request.form['dateNaissance']
    NumTel = request.form['numTel']
    disponibilite = request.form['disponibilite']
    experience = request.form['experience']
    CV = request.files['cv']
    message = request.form['message']
    filename = secure_filename(CV.filename)

    etat = 'Nouvelle'
    statue = 'NonConfirme'
    token = s.dumps(email, salt="email_confirm")
    file = filename
    resultat = Candidat.query.filter_by(email=email).count()
    if resultat > 0:
        return jsonify("email est déjà utiliser")

    new_candidat = Candidat(nom, prenom, email, dateNaissance, NumTel,
                            disponibilite, experience, filename, message, etat,
                            statue)
    upload_file(CV)
    CV.save(os.path.join(uploads_dir, CV.filename))
    db.session.add(new_candidat)
    send_mail(email, app, token)
    db.session.commit()

    return jsonify("Candidature déposer veuiller confirmer votre email")
Exemplo n.º 4
0
def run(parsed):
    recips = map(process_recip, parsed.get('~_PersonalName', []))
    subject = parsed.get('~subject', [''])[0]
    body = parsed.get('~message', [''])[0]
    attach = 'include_files' in parsed
    from send_mail import send_mail
    send_mail(recips, subject, body, attach)
Exemplo n.º 5
0
def sign(m, d, user, smtp_host, mail_username, mail_password):

    '''
    签到,并且发送邮件提醒,成功返回True,失败返回False
    '''
    for _ in range(try_times):
        try:
            time.sleep(delay)
            headers['Cookie'] = user['cookie']
            r = requests.post('https://m.nuaa.edu.cn/ncov/wap/default/save',
                              data=post_data.format(int(time.time()), m, d - 1), headers=headers)
            print('sign statue code:', r.status_code)
            print('sign return:', r.text)
            r.encoding = 'utf-8'
            
            if r.text.find('成功') >= 0:
                print('打卡成功')
                if user['receiver_mail'] != '':
                    send_mail(mail_username, mail_password, smtp_host,
                              user['receiver_mail'], '打卡成功', '打卡成功', user['name'], '打卡姬')
                return True
            else:
                print('打卡失败,尝试重新登陆')
                user['cookie'] = login(user['student_id'], user['student_password'])
        except:
            print('尝试失败')
            pass
            # print(r.request.body)
    if user['receiver_mail'] != '':
        send_mail(mail_username, mail_password, smtp_host,
                  user['receiver_mail'], '打卡失败', '打卡事变', user['name'], '打卡姬')
    return False
Exemplo n.º 6
0
    def work(self):
        print(f'开始选 {self.new_course_teacher} 的《{self.new_course_name}》...')

        count = 1
        while True:
            print(f'正在第 {count} 次尝试...')
            count += 1

            url = 'https://jw.ustc.edu.cn/ws/for-std/course-select/add-request'
            data = {
                'studentAssoc': self.student_ID,
                'lessonAssoc': self.new_course_ID,
                'courseSelectTurnAssoc': self.course_select_turn_ID,
                'scheduleGroupAssoc': '',
                'virtualCost': '0'
            }

            # TODO: 用约 2 行代码获取 request_ID
            request_ID = 'request_ID'

            time.sleep(self.period * 0.5 * uniform(0.6, 1.4))

            result = self.process_request_ID(request_ID)

            if result is None:
                print('响应为空,重试...')
            elif result['success'] is True:
                message = f'成功选择 {self.new_course_teacher} 的《{self.new_course_name}》,程序退出!'
                print(message)
                send_mail(message, message)
                break
            else:
                print('直选失败,失败原因: ' + result['errorMessage']['textZh'])

            time.sleep(self.period * 0.5 * uniform(0.6, 1.4))
Exemplo n.º 7
0
 def db_update(self, dbconn):
     ''' Function loads info about file update to db.
     '''
     if self.fileinfo['update_error'] == 0:
         dbconn.successful_update(self.fileinfo['reportID'],
                                  self.fileinfo['update_time'])
     else:
         # 6 - problem with Outlook. Send mail using SQL Server.
         if self.fileinfo['update_error'] == 6:
             dbconn.send_emergency_mail(self.fileinfo['reportName'])
         else:
             send_mail(
                 subject='(Ошибка обновления) ' +
                 self.fileinfo['reportName'],
                 HTMLBody=('ID ошибки: ' +
                           str(self.fileinfo['update_error']) + '. ' +
                           self.errors[self.fileinfo['update_error']] +
                           '<br>' + 'Отчёт: ID ' +
                           str(self.fileinfo['reportID']) + ' <a href="' +
                           path.join(self.fileinfo['fpath'],
                                     self.fileinfo['fname']) + '">' +
                           self.fileinfo['reportName'] + '</a>.'),
                 rName=self.fileinfo['reportName'])
         dbconn.failed_update(self.fileinfo['reportID'],
                              self.fileinfo['update_time'],
                              self.fileinfo['update_error'])
     # clear info about last file
     for key in self.fileinfo.keys():
         self.fileinfo[key] = None
Exemplo n.º 8
0
def submit():
    if request.method == 'POST':
        # Getting form data
        customer = request.form['customer']
        dealer = request.form['dealer']
        rating = request.form['rating']
        comments = request.form['comments']

        # Prompt message if customer or dealer fields are blank
        if customer == "" or dealer == "" or comments == "":
            return render_template('index.html',
                                   message='Please enter required fields')

        # Check if user already submitted feedback
        if db.session.query(Feedback).filter(
                Feedback.customer == customer).count() == 0:
            # If user hasn't submitted feedback yet
            data = Feedback(customer, dealer, rating, comments)
            # Add to database
            db.session.add(data)
            db.session.commit()
            # Send email notification
            send_mail(customer, dealer, rating, comments)
            # Show rendered confirmation page
            return render_template('success.html')

        # If user already present in database show prompt
        return render_template('index.html',
                               message='You have already submitted feedback')
Exemplo n.º 9
0
def submit():
    if request.method == 'POST':
        time = datetime.now()
        name = request.form['name']
        sleep = request.form['Hours of sleep']
        meals = request.form['Number of meals']
        work = request.form['Number of work hours']
        try:
            exercise = request.form['Exercise check']
        except:
            exercise = 0
        try:
            meditation = request.form['Meditation check']
        except:
            meditation = 0
        try:
            happiness = request.form['Happiness']
        except:
            return render_template('index.html',
                                   message='Please enter all fields!')
        if name == '' or sleep == '' or meals == '' or work == '' or happiness == '':
            return render_template('index.html',
                                   message='Please enter all fields!')

        data = Wellness(time, name, sleep, meals, work, exercise, meditation,
                        happiness)
        db.session.add(data)
        db.session.commit()
        send_mail(time, name, sleep, meals, work, exercise, meditation,
                  happiness)
        return render_template('Success.html')
Exemplo n.º 10
0
def webhookevent():

    if request.method == 'POST':
        req = request.get_json()

        iD = req.get("id")
        name = req.get("name")
        resource = req.get("resource")
        event = req.get("event")
        filter = req.get("filter")
        orgId = req.get("orgId")
        createdBy = req.get("createdBy")
        appId = req.get("appId")
        ownedBy = req.get("ownedBy")
        status = req.get("status")
        actorId = req.get("actorId")
        data_id = req['data']['id']
        data_roomId = req['data']['roomId']
        data_personId = req['data']['personId']
        data_personEmail = req['data']['personEmail']
        data_created = req['data']['created']

        print(iD)
        print(name)
        print(resource)

        send_mail(iD, name, resource, event, filter, orgId, createdBy, appId,
                  ownedBy, status, actorId, data_id, data_roomId,
                  data_personId, data_personEmail, data_created)
        return "okay", 200
    elif request.method == 'GET':
        return "Yes, this works okay."
Exemplo n.º 11
0
def get_chapters(path, url, folder, chapter_list, send):
    try:
        chapters_folder = os.getcwd() + folder
        print(chapters_folder)
        if not os.path.isdir(chapters_folder):
            os.mkdir(chapters_folder)
    except OSError:
        print("Directory creation failed.")
    finally:
        # constants
        class_name = "separator"
        # loop over all chapters
        for chapter_number in chapter_list:
            new_chapter_folder = os.getcwd() + folder + chapter_number
            if os.path.isdir(new_chapter_folder):
                print("! chapter " + chapter_number + " already downloaded")
            else:
                os.mkdir(new_chapter_folder)
                chapter_url = "https://w16.read-onepiece.com/manga/one-piece-chapter-" + chapter_number + "/"
                # download chapter
                download(path, chapter_url, chapter_number, class_name,
                         new_chapter_folder)
                print("- chapter " + chapter_number + " downloaded")
                # zip files
                zipf = zipfile.ZipFile(new_chapter_folder + '.zip', 'w',
                                       zipfile.ZIP_DEFLATED)
                zipdir(folder, chapter_number, zipf)
                zipf.close()
                print("- zip created")
                # send email
                if send:
                    send_mail(chapter_number)
                    print("- email sent")
Exemplo n.º 12
0
def wait_for_available(driver):
    save_html(driver, "slots")
    tentative = 0

    while tentative < MAX_TENTATIVE:
        log.info(f"Trying at {datetime.datetime.now()}")
        slots = driver.find_elements_by_xpath("//input[@class='disponibile']")

        if slots:
            log.info(f"{len(slots)} slots found.")
            send_mail(
                EMAIL,
                subject="[BOT] Free slots found!",
                body=
                f"{datetime.datetime.now()}: {len(slots)} slots found!\nWe select the first available."
            )
            slots[0].click()
            driver.save_screenshot(
                f"{datetime.datetime.now()}_slots_found.png")
            driver.find_element_by_id("checkoutNextStep").click()
            return
        else:
            tentative += 1
            log.info(f"No slots available. Retrying in {RETRY_TIME} seconds")
            time.sleep(RETRY_TIME)
            driver.refresh()
            time.sleep(3)
            click_next_step(driver)

    sys.exit(0)
Exemplo n.º 13
0
    def work(self):
        print(
            f'开始将《{self.new_course_name}》从 {self.old_course_teacher} 换到 {self.new_course_teacher}'
        )
        count = 1
        while True:
            print(f'正在第 {count} 次尝试...')
            count += 1

            raise NotImplementedError

            time.sleep(self.period * 0.5 * uniform(0.6, 1.4))

            result = self.process_request_ID(request_ID)

            if result is None:
                print('响应为空,重试...')
            elif result['success'] is True:
                message = f'成功换班到 {self.new_course_teacher} 的《{self.new_course_name}》,程序退出!'
                print(message)
                send_mail(message, message)
                break
            else:
                print('换班失败,失败原因: ' + result['errorMessage']['textZh'])

            time.sleep(self.period * 0.5 * uniform(0.6, 1.4))
Exemplo n.º 14
0
def submit():
    if request.method == "POST":
        customer = request.form["customer"]
        dealer = request.form["dealer"]
        rating = request.form["rating"]
        comments = request.form["comments"]

        # validation
        if customer == "" or dealer == "":
            return render_template(
                "index.html",
                message="Make sure you filled out all the fields")

        # prevent user from submitting twice
        if db.session.query(Feedback).filter(
                Feedback.customer == customer).count() == 0:
            data = Feedback(customer, dealer, rating, comments)

            # add the data to the database
            db.session.add(data)

            # save the changes
            db.session.commit()

            send_mail(customer, dealer, rating, comments)

            return render_template("success.html")

        return render_template("index.html",
                               message="You have already submitted")
Exemplo n.º 15
0
def submit():
    if request.method == 'POST':
        customer = request.form['customer']
        dealer = request.form['dealer']
        rating = request.form['rating']
        comments = request.form['comments']

        # print(customer, dealer, rating, comments)

        # Validtion checks
        if customer == '' or dealer == '':
            return render_template('index.html',
                                   message='Please enter required fields!!')

        #Quering  from the Model if the customer already exists
        if db.session.query(Feedback).filter(
                Feedback.customer == customer).count() == 0:
            data = Feedback(customer, dealer, rating, comments)
            db.session.add(data)
            db.session.commit()
            send_mail(customer, dealer, rating, comments)
            return render_template('success.html')

        #Runs if above is not true
        #like an else stmt
        return render_template('index.html',
                               message='You have already submitted feedback!!')
Exemplo n.º 16
0
def backup_mariadb(params):
    """ MariaDB mysqldump - full database dump. Backups are PIPED to AWS S3
    backups are run from dbaas container. Require connection to container db 
    object. Requires AWS S3 tools on dbaas.
    """
    con_name = params['dbname']
    passwd = Config.accounts['MariaDB']['admin_pass']
    (c_id, dbengine) = admin_db.get_container_type(con_name)
    data = admin_db.get_container_data('', c_id)
    port = data['Info']['Port']
    (backupdir, backup_id) = container_util.create_backupdir(con_name)
    if 'backup_type' in params:
        backup_type = params['backup_type']
    else:
        backup_type = 'NA'
    bucket = os.environ.get('AWS_BUCKET')
    s3_url = bucket + '/' + con_name + backupdir
    s3_filename = s3_url + '/dump' + backup_id + '.sql'
    s3_infopath = s3_url + '/infoschema' + backup_id + '.sql'

    # mysqldump to S3 Backups
    template = "/usr/bin/mysqldump --host %s --port %s --user=root " % (
        Config.container_ip, port)
    template += "--password=%s "
    dump_cmd = template + "--all-databases"
    cmd = dump_cmd % passwd
    aws_cmd = "aws --only-show-errors s3 cp - %s --sse" % s3_filename
    admin_db.backup_log(c_id,
                        con_name,
                        'start',
                        backup_id,
                        backup_type,
                        url='',
                        command=cmd,
                        err_msg='')
    print("DEBUG: mysqdump command: %s" % cmd)
    p1 = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
    p2 = subprocess.Popen(aws_cmd.split(),
                          stdin=p1.stdout,
                          stdout=subprocess.PIPE)
    (processed, err) = p2.communicate()
    if processed and len(processed) > 0:
        message = "MariaDB Backup error.  Container: %s" % con_name
        message += "Error message: %s" % processed
        print(message)
        send_mail("DB4SCI: MariaDB backup", message)
    else:
        message = '\nExecuted MariaDB dump comand:\n    '
        message += dump_cmd % 'xxxxx'
        message += "\nResult:\n" + processed
        message += "Dump file: %s\n\n" % s3_filename
        admin_db.backup_log(c_id,
                            con_name,
                            'end',
                            backup_id,
                            backup_type,
                            url=s3_filename,
                            command=cmd,
                            err_msg=processed)
    return "command", message
Exemplo n.º 17
0
def get_ball(reb_count,red_max,blue_count,blue_max):
    # 循环一百遍,一遍代表一年
    for i in range(0,100):
        # 红球(5个,最大35)
        red_ball = luck(reb_count,red_max)
        red_ball.append('-')

        # 篮球(2个,最大12)
        blue_ball = luck(blue_count,blue_max)
        # 如果第3个红球<=10,则再生成一次
        if red_ball[2] <= '10':
            continue
        else:
            # 幸运号码
            ball_list = red_ball+blue_ball
            # 把号码格式化一下,好看点
            beautiful_ball = ''
            for j in range(0,len(ball_list)):
                beautiful_ball += ball_list[j] + ' '
            print(beautiful_ball)

            # 生成图片
            create_image.create_image(beautiful_ball)

            # 发送邮件
            send_mail.send_mail()
            break
Exemplo n.º 18
0
def submit():
    if request.method == 'POST':
        customer = request.form['customer']
        developer = request.form['developer']
        rating = request.form['rating']
        comments = request.form['comments']
        # print(customer, developer, rating, comments)  Test to see if form data is submitted

        # Output alert if customer or developer is blank
        if customer == '' or developer == '':
            return render_template('index.html',
                                   message='Please enter required fields')

        # Database filters to Feedback model's customer name.
        # If customer name in feedback has the amount of 0, customer does not exist in database yet
        if db.session.query(Feedback).filter(
                Feedback.customer == customer).count() == 0:
            data = Feedback(customer, developer, rating, comments)
            # Add data entered in fields
            db.session.add(data)
            # Commit data to database
            db.session.commit()
            # Send email after successful feedback
            send_mail(customer, developer, rating, comments)
            return render_template('success.html')
        # else return user to index
        return render_template('index.html',
                               message='You have already submitted feedback')
 def send_status_mail(self, server_id, event, message):
     # Get server entry and find configured e-mail
     servers = self._status_serverDb.get_server(
         {"id" : server_id}, detail=True)
     if not servers:
         msg = "No server found with server_id " + server_id
         self._smgr_log.log(self._smgr_log.ERROR, msg)
         return -1
     server = servers[0]
     email_to = []
     if 'email' in server and server['email']:
         email_to = self.get_email_list(server['email'])
     else:
         # Get cluster entry to find configured e-mail
         if 'cluster_id' in server and server['cluster_id']:
             cluster_id = server['cluster_id']
             cluster = self._status_serverDb.get_cluster(
                 {"id" : cluster_id}, detail=True)
             if cluster and 'email' in cluster[0] and cluster[0]['email']:
                     email_to = self.get_email_list(cluster[0]['email'])
             else:
                 self._smgr_log.log(self._smgr_log.DEBUG,
                                    "cluster or server doesn't configured for email")
                 return 0
         else:
             self._smgr_log.log(self._smgr_log.DEBUG, "server not associated with a cluster")
             return 0
     send_mail(event, message, '', email_to,
                                 self._status_thread_config['listen_ip'], '25')
     msg = "An email is sent to " + ','.join(email_to) + " with content " + message
     self._smgr_log.log(self._smgr_log.DEBUG, msg)
Exemplo n.º 20
0
def update_auth_logs():
    cmd = ["tail", "/var/log/auth.log"]
    email = False
    try:
        proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=DEVNULL)
    except Exception as e:
        return
    with open(LOG_FILE_PATH, "w") as logfile:
        for line in proc.stdout.readlines():
            line_timestamp = str(line[0:15])
            line_timestamp = time.mktime(
                datetime.datetime.strptime(
                    line_timestamp + str(datetime.datetime.now().year),
                    "b'%b %d %H:%M:%S'%Y").timetuple())
            if b'USER=root' in line and b'mirador' not in line:
                logfile.write(str(line))
                email = True
            if b'sshd' in line:
                logfile.write(str(line))
                email = True
        logfile.close()
    if email:
        with open(LOG_FILE_PATH, "r") as logfile:
            log("Something found in Auth Logs ")
            send_mail("Alert in authlogs ", logfile.read(), EMAIL_TO)
    f = open(LAST_REPORTED_PATH, "w")
    try:
        f.write(str(line_timestamp))
    except UnboundLocalError:
        #log("No auth logs found")
        pass
    f.close()
Exemplo n.º 21
0
def run(parsed):
		recips = get_emails(parsed)
		subject = parsed.get('~subject', '')
		body = parsed.get('~message', '')
		attach = get_attachment(parsed)
		from send_mail import send_mail
		send_mail(recips, subject, body, attach)
Exemplo n.º 22
0
def grab_goods_and_save(scan_config, db_config):
    price_json = requests.get("http://p.3.cn/prices/get?skuid=%s" %
                              scan_config.j_id).json()[0]
    print('j_id %s price_json %s' % (scan_config.j_id, price_json))
    goods_price = GoodsPrice(scan_config.j_id, price_json['op'],
                             price_json['m'], datetime.datetime.now())
    db = MySQLdb.connect(db_config.host,
                         db_config.user,
                         db_config.password,
                         db_config.db,
                         charset='utf8')
    cursor = db.cursor()
    insert_sql = 'INSERT INTO goods_price (j_id, current_price, price, create_time) VALUES ("%s", %s, %s, "%s")' % (
        goods_price.j_id, goods_price.current_price, goods_price.price,
        goods_price.create_time.strftime('%Y-%m-%d %H:%M:%S'))
    print('start insert price %s' % goods_price)
    try:
        cursor.execute(insert_sql)
        db.commit()
        print('insert success')
    except Exception as e:
        print('insert error %s' % e)
        db.rollback()
    select_sql = 'SELECT id, j_id, name, url, comment, create_time FROM goods_message WHERE j_id = "%s"' % scan_config.j_id
    cursor.execute(select_sql)
    result = cursor.fetchall()[0]
    db.close()
    goods_message = GoodsMessage(result[1], result[2], result[3], result[4],
                                 result[5])
    # print ('good message %s' % goods_message)
    send_mail.send_mail(goods_message, goods_price.current_price)
Exemplo n.º 23
0
def submit():
    if request.method == 'POST':
        EmailID = request.form['EmailID']
        Employee = request.form['Employee']
        Location = request.form['Location']
        EmployeeID = request.form['EmployeeID']
        Designation = request.form['Designation']
        Department = request.form['Department']
        rating = request.form['rating']
        comments = request.form['comments']
        # print(employee, department, rating, comments)
        if Employee == '' or Department == '':
            return render_template('index.html',
                                   message='Please enter required fields')
        if db.session.query(Feedback).filter(
                Feedback.Employee == Employee).count() == 0:
            data = Feedback(EmailID, Employee, Location, EmployeeID,
                            Designation, Department, rating, comments)
            db.session.add(data)
            db.session.commit()
            send_mail(EmailID, Employee, Location, EmployeeID, Designation,
                      Department, rating, comments)
            return render_template('index2.html')

        return render_template('index.html',
                               message='You have already submitted feedback')
Exemplo n.º 24
0
def submit():
    if request.method == 'POST':
        customer = request.form['customer']
        dealer = request.form['dealer']
        rating = request.form['rating']
        comments = request.form['comments']

        # Add validations to the form and display a message if otherwise
        if customer == "" or dealer == "":
            return render_template('index.html',
                                   message="Please enter required fields!")

        # Only allow new customers to submit feedback
        if db.session.query(Feedback).filter(
                Feedback.customer == customer).count() == 0:
            data = Feedback(customer, dealer, rating, comments)
            db.session.add(data)
            db.session.commit()
            ## SEE NOTES AT THIS POINT
            # After the data has been saved on the PSQL database, send an email now
            send_mail(customer, dealer, rating, comments)
            return render_template('success.html')
        else:
            return render_template('index.html',
                                   message="You cannot submit feedback twice!")
Exemplo n.º 25
0
def sending_mail():
    index, name_list, quantity_list, status_list, date_list = db.show_all_data(
    )
    message = sm.table(
        df.data_frame(index, name_list, quantity_list, status_list, date_list))
    sm.send_mail(message)
    return render_template('mail.html')
Exemplo n.º 26
0
def submit():
	#Makes sure this action append under the POST request
	if request.method == 'POST':
		#Gathers info form the form (checks the fields with the 'names' specified below)
		customer = request.form['customer']
		dealer = request.form['dealer']
		rating = request.form['rating']
		comments = request.form['comments']
		#if info is not complete
		if customer == '' or dealer == '':
			#Creates and renders 'message'. 
			return render_template('index.html', message = '***Please enter the required fields.***')
		
		#Checks the same customer doesn't submit more than one feddback.
		if db.session.query(Feedback).filter(Feedback.customer == customer).count() == 0:
			data = Feedback(customer, dealer, rating, comments)
			db.session.add(data)
			db.session.commit()
			send_mail(customer, dealer, rating, comments)
			return render_template('success.html')
		return render_template('index.html', message = 'You have already submitted feedback.')

	elif request.method == 'GET':
		listComments = Feedback.query.all()
		return render_template('list_comments.html', comments = listComments)
Exemplo n.º 27
0
 def handle_node_event(self, network, node, value):
   if self.alarm_on and not self.in_alarm_state and node.node_id in self.nodes_in_alarm and self.node_ids[node.node_id]['type'] == self.SENSOR and value > 0:
     self.in_alarm_state = True
     self.turn_sirens_on()
     send_mail(self.node_ids[node.node_id]['name'])
   elif self.node_ids[node.node_id]['type'] != self.SENSOR:
     print('Louie signal : Node event : {0}. value: {1}'.format(node, value))
Exemplo n.º 28
0
def main():
    file = 'сотрудники 1553.txt'
    list_persons, list_mails = list_of_persons_and_mails(file)
    url_ege = 'http://rcoi.mcko.ru/index.php?option=com_content&view=article&id=898&Itemid=197'
    url_gia = 'http://rcoi.mcko.ru/index.php?option=com_content&view=article&id=1033&Itemid=211'
    cod_text = read_html_cod(url_ege, url_gia)
    bad_man = write_lists_of_persons_records(list_persons, cod_text)
    bad_man = [i for i in bad_man if i is not None]
    index_bad_man = [
        list_persons.index(i) for i in list_persons if i in bad_man
    ]
    list_mails = [
        i for i in list_mails if not list_mails.index(i) in index_bad_man
    ]
    list_of_files = [[i + '.xls'] for i in list_persons]
    list_mails_bad_man = [
        i for i in list_mails if list_mails.index(i) in index_bad_man
    ]
    list_mails = [[i] for i in list_mails]
    from_email = '*****@*****.**'

    subject = ''
    for send_to, files in zip(list_mails, list_of_files):
        text = 'Ваше расписание экзаменов.'
        send_mail(from_email,
                  send_to,
                  subject,
                  text,
                  files,
                  server='smtp.gmail.com')
    for to_email in list_mails_bad_man:
        text = 'Вы не участвуете в проведении экзаменов'
        send(text, subject, from_email, to_email, host='smtp.gmail.com')
Exemplo n.º 29
0
def submit():
    # Checks that the submit is a POST method and not a GET
    if request.method == 'POST':
        # Gets information from the form variables
        customer = request.form['customer']
        dealer = request.form['dealer']
        rating = request.form['rating']
        comments = request.form['comments']
        # print(customer, dealer, rating, comments)

        # Checks if customer and dealer are empty
        if customer == '' or dealer == '':
            # if fields are empty, index/html is rendered and message is output to user
            return render_template('index.html',
                                   message='Please enter required fields')

        # Checks if customer doesnt already exist
        # Commits feedback to db, renders success page after form submission
        if db.session.query(Feedback).filter(
                Feedback.customer == customer).count() == 0:
            data = Feedback(customer, dealer, rating, comments)
            db.session.add(data)
            db.session.commit()

            # Connect and send email
            send_mail(customer, dealer, rating, comments)

            # Render success.html page
            return render_template('success.html')

        # If customer is duplicated, index rendered and message output to user
        return render_template('/index.html',
                               message='You have already submitted feedback')
Exemplo n.º 30
0
def submit():
    if request.method == 'POST':
        customer = request.form['name']
        driver = request.form['driver']
        rating = request.form['ratings']
        comments = request.form['comments']
        print(customer, driver, rating, comments)

        # simple input validation
        if customer == '' or driver == '':
            return render_template(
                'index.html',
                message="Please do not leave the required fields blank!")

        if db.session.query(Feedback).filter(
                Feedback.customer == customer).count() == 0:
            data = Feedback(customer, driver, rating, comments)
            db.session.add(data)
            db.session.commit()

            # sends email
            send_mail(customer, driver, rating, comments)
            return render_template('success.html')
            print("success")
        return render_template('index.html',
                               message="You already submitted a feedback!")
Exemplo n.º 31
0
def submit():
    if request.method == 'POST':
        customer = request.form['customer']
        dealer = request.form['dealer']
        rating = request.form['rating']
        comments = request.form['comments']
        useremail = request.form['useremail']
        #print(customer, dealer, rating, comments, useremail)
        if customer == '' or dealer == '':
            return render_template('index.html',
                                   message="Please enter required fields")

        #prevent a user keep submitting feedback over again and again
        if db.session.query(Feedback).filter(
                Feedback.customer == customer).count() == 0:
            data = Feedback(customer, dealer, rating, comments, useremail)
            db.session.add(data)
            db.session.commit()

            #send email after db commits
            send_mail(customer, dealer, rating, comments, useremail)

            return render_template('success.html')
        return render_template('index.html',
                               message="You've submitted feedback")
Exemplo n.º 32
0
def submit():
    # To make shure that this is post request only
    if request.method == 'POST':
        customer = request.form['customer']
        dealer = request.form['dealer']
        rating = request.form['rating']
        comments = request.form['comments']

        # To make sure that user enters customer and dealer fields
        if customer == '' or dealer == '':
            return render_template('index.html',
                                   message='Please enter required fields')

        # lets make check that only one custumer can submit only one feedback and not more.
        if db.session.query(Feedback).filter(
                Feedback.customer == customer).count() == 0:
            # basically we count customers and if customer is ZERO menaing it does not exist
            data = Feedback(customer, dealer, rating,
                            comments)  # we make an instance of model
            db.session.add(data)
            db.session.commit()  #new data will be saved in database

            send_mail(customer, dealer, rating, comments)
            return render_template(
                'success.html')  # return success page if all good
        return render_template('index.html',
                               message='You have already submitted feedback')
Exemplo n.º 33
0
 def is_rebot(self, content):
     content = self.format_content(content)
     result = re.findall(r'我真滴不是机器人', content)
     if len(result) > 0:
         send_mail('机器人', '快填验证码!')
         return True
     else:
         return False
Exemplo n.º 34
0
def big_down(movies=['的'], start_time='2014-03-01', end_time='2014-03-11'):
    index = 0
    for movie in movies:
        index += 1
        start_work_time = datetime.datetime.now()
        Controller(movie, start_time, end_time).start()
        con = '"' + movie + '" ' + start_time + ' -- ' + end_time + ' 数据已经爬取完成。' + '\nStart word time:' + str(start_work_time) + '.\nEnd word time:' + str(datetime.datetime.now())
        send_mail('Spider END.%s' % index, con)
Exemplo n.º 35
0
 def is_rebot(self, content, url='http://s.weibo.com/wb/568&timescope=custom:2014-05-17%3A2014-05-17&xsort=time&nodup=1'):
     content = self.format_content(content)
     result = re.findall(r'我真滴不是机器人', content)
     if len(result) > 0:
         send_mail('机器人', ('user: '******'\n pwd:' + PASSWORD + '\n' + url))
         return True
     else:
         return False
Exemplo n.º 36
0
 def process_data(self, data):
     server_multithread.logger.info(data)
     if data.startswith('Alarm'):
         server_multithread.logger.info('Alarm received')
         self.conn.send('ACK')
         send_mail()
     else:
         server_multithread.logger.info('Unknow command received')
         self.conn.send('Unknow command')
Exemplo n.º 37
0
    def mail_error(self, error):

        """Send mail if Connect fail"""

        conf.MAILCONTENT = conf.MAILCONTENT.join(str(error))
        send_mail.send_mail(conf.MAILUSERNAME, conf.MAILSENDMAIL,
                            conf.MAILSUBJECT, conf.MAILCONTENT,
                            conf.MAILTOLIST, conf.MAILSENDER,
                            conf.MAILPASSWORD)
Exemplo n.º 38
0
def hour_down(movies=['的'], start_time='2014-03-01-04', end_time='2014-03-11-07', pro=True,city=True):
    index = 0
    for movie in movies:
        print movie
        index += 1
        start_work_time = datetime.datetime.now()
        Controller(movie, start_time, end_time).spider_day_hour(pro, city)
        con = '"' + movie + '" ' + start_time + ' -- ' + end_time + ' 数据已经爬取完成。' + '\nStart word time:' + str(start_work_time) + '.\nEnd word time:' + str(datetime.datetime.now())
        send_mail('Spider END.%s' % index, con)
Exemplo n.º 39
0
def reminder():
    import send_mail
    print 'reminder'
    text = '''Hi All,
    泊车新版本将在今天晚上【21:00】开始编译,如有新的代码更新,请于今晚 21:00 前提交到svn。
    泊车新版本编译完成后,后将预定系统中没有预订的设备进行自动升级,如果某台设备需要保留旧版本,
    请在预订系统中将其预订。

    附:
    设备预订系统地址如下:
    http://192.168.1.164/mrbs/web/
    '''
    send_mail.send_mail(sub='[PARK BUILD REMINDER]',content=text)
Exemplo n.º 40
0
def run(parsed):
		import json
		recips = get_emails(parsed)
		subject = parsed.get('~subject', '')
		body = parsed.get('~message', '')
		attach = get_attachment(parsed)
		prefs = json.loads(open("preferences.json").read())
		
		client = prefs.get('client', 'mail.app')
		if client == 'mail.app':
			from send_mail import send_mail
			send_mail(recips, subject, body, attach)
		elif client == 'gmail':
			import gmail
			gmail.open(recips, subject, body)
Exemplo n.º 41
0
def test_send_mail():
    # Test send_mail.py
    # The send_mail function only works inside the firewall.
    from send_mail import send_mail
    email_address = '*****@*****.**'
    subject = 'test.py'
    assert send_mail(email_address=email_address, subject=subject, body="") == None
Exemplo n.º 42
0
    def post_condition(self):
        print "buy list {}".format(self.buy_list)
        print "sell list {}".format(self.sell_list)

        content = ""
        for i in self.buy_list:
            content += "buy {};".format(i)
        for i in self.sell_list:
            content += "sell {};".format(i)
        for i in self.candidate_sell_list:
            content += "candidatesell {};".format(i)

        ISOTIMEFORMAT='%Y-%m-%d %X'
        send_mail(MAIL_TO1, "{} decision".format(time.strftime( ISOTIMEFORMAT)),content)
        send_mail(MAIL_TO2, "{} decision".format(time.strftime( ISOTIMEFORMAT)),content)

        self.record_new_decision(self.stock_record_newadd_dict)
Exemplo n.º 43
0
def ship2device():
    from mysql_handler import get_except_ip
    global ip_except
    ip_except = get_except_ip()
    print ip_except

    for item in range(211, 212):
        ip = '192.168.1.' + str(item)
        global ip_except
        if ip in ip_except:
            print 'ip is except'
        else:
            global ip_list
            ip_list.append(ip)
            print ip
            print pack_name
            from run_cmd import update
            update(ip, pack_name)

    time.sleep(120)

    global pack_url
    global pack_url1
    text = 'HI ALL, \n泊车版本已经打包完成, 你可以在如下地址获取到最新的泊车版本\n' + pack_url + '\n' + pack_url1
    text = text + "\n\n更新内容可在http://192.168.1.164:8080/job/PARK/lastBuild/changes 获得.\n\n"
    text = text + "\n\n目前如下设备已经升级到最新版本([X]代表已升级, [ ]代表未升级):\n\n"

    from run_cmd import run_cmd
    for item in range(211, 212):
        ip = '192.168.1.' + str(item)
        version_text = run_cmd(ip, 'cat /var/version/version')
        v = version_text.split('=')
        version_text = v[1]
        global version
        if ip in ip_except:
            text = text + '[ ] ' + ip + '\n'
        else:
            text = text + '[X] ' + ip + '      ' + version_text + '\n'

    import send_mail
    send_mail.send_mail(sub="[PARK BUILD FINISHED] " + pack_name, content=text)
Exemplo n.º 44
0
def main():
    file = 'сотрудники 1553.txt'
    list_persons,list_mails = list_of_persons_and_mails(file)
    url_ege = 'http://rcoi.mcko.ru/index.php?option=com_content&view=article&id=898&Itemid=197'
    url_gia = 'http://rcoi.mcko.ru/index.php?option=com_content&view=article&id=1033&Itemid=211'
    cod_text = read_html_cod(url_ege,url_gia)
    bad_man = write_lists_of_persons_records(list_persons, cod_text)
    bad_man=[i for i in bad_man if i is not None]
    index_bad_man = [list_persons.index(i) for i in list_persons if i in bad_man]
    list_mails = [i for i in list_mails if not list_mails.index(i) in index_bad_man ]
    list_of_files = [[i + '.xls'] for i in list_persons]
    list_mails_bad_man = [i for i in list_mails if list_mails.index(i) in index_bad_man ]
    list_mails = [[i] for i in list_mails]
    from_email = '*****@*****.**'

    subject = ''
    for send_to, files in zip(list_mails,list_of_files):
        text = 'Ваше расписание экзаменов.'
        send_mail(from_email, send_to, subject, text, files, server='smtp.gmail.com')
    for to_email in list_mails_bad_man:
        text = 'Вы не участвуете в проведении экзаменов'
        send(text, subject, from_email, to_email, host='smtp.gmail.com')
Exemplo n.º 45
0
def main():
    mail_list = ['*****@*****.**']
    now = time.strftime("%Y-%m-%d")
    days = 5
    result = Find_Vol_Amplification(now)

    file("vol_amp_%s.txt" %now, "w").write(result)

    print "Sending mail...",
    if send_mail.send_mail(mail_list, "Vol amplificaion %s" %now, result):
        print "OK"
    else:
        print "Failed"
Exemplo n.º 46
0
def flat_spider(email, top_price, max_pages=1):
    page = 1
    while page <= max_pages:
        url = "https://www.anonse.com/lista/rejon/warszawski/kategoria/nieruchomosci/podkategoria/mieszkania/rt/sprzedam/" + str(page)
        r = requests.get(url)
        c = r.content

        soup = BeautifulSoup(c, "html.parser")

        all_properties = soup.find_all("a", {"class": "center2"})

        first_prop_name = all_properties[0].text.split()[0]
        first_prop_price = int(all_properties[0].find_all("span", {"style": "font-size:10px; "})[0].text.replace(" ", "").replace("zł", ""))
        print(first_prop_name)
        print(str(first_prop_price) + " PLN")
        print("=========================")

        cheap_pairs = []

        for prop in all_properties:
            price = prop.find_all("span", {"style": "font-size:10px; "})[0].text.replace(" ", "").replace("zł", "")
            city = prop.find_all("div", {"class": "atrybut_miasto"})[0].text.split()[0]
            prop_name = prop.text.split()[0]
            href = 'https://www.anonse.com' + prop.get('href')

            if city == "WARSZAWA":
                if 50000 < int(price) < int(top_price):
                    cheap_pairs.append([prop_name, str(price) + "zł", href])

        # print(cheap_pairs)
        message_generator(cheap_pairs)

        with open("message.txt", "r") as myfile:
            data = myfile.read().replace('\n', '<br><br>')
            if len(data) > 0:  # prevent from sending mail if results are 0
                send_mail(email, data)

        page += 1
def main(argv):
    if len(argv) == 1:
        log_list = service_list
    else:
        log_list = [argv[1]]
    for each in log_list:
        fp = open(os.path.join(JSON_LOG_PATH, each + ".json"))
        json_content = json.loads(fp.read())
        c = CreateHtml(json_content, each)
        c.get_template()
        c.get_rendered()
        c.save_html(os.path.join(HTML_LOG_PATH, each+'.html'))
    #send_mail
    print log_list
    for each in log_list:
        fp = open(os.path.join(HTML_LOG_PATH, each+'.html'),"r")
        content = fp.read()
        fp.close()
        if send_mail(mailto_list, "GoAccess Nginx", each, content):
            print "Mail Send Successed!"
        else:
            print "Mail Send Failed!"
Exemplo n.º 48
0
def  alarm_mail(subject,context):
     send_mail.send_mail(send_mail.mailto_list,subject,context)
     print  'send  ok'
Exemplo n.º 49
0
    
    sql = 'select count(id) from dbn_purchase_qualification where beginTime=' + str(start_timestamp) + ' and endTime=' + str(end_timestamp);
    print sql
    cursor.execute(sql)
    results = cursor.fetchall()
    for row in results:
      result_str += "分享人数:" + str(row[0]) + "\n"
    
    # 订单数量
    # 秒杀产品付款订单
    sql = "select count(A.id) from dbn_product_order as A,dbn_product_order_info as B,dbn_seller_goods as C where C.flash_start_time >=" +  str(day_begin_timestamp) + ' and C.flash_start_time <= ' + str(day_end_timestamp) + ' and A.id=B.order_id and B.goods_id=C.id and A.status>=2 and A.status<99'
    print sql
    cursor.execute(sql)
    results = cursor.fetchall()
    for row in results:
      result_str += "成交订单数:" + str(row[0]) + "\n"
    
    # 秒杀产品未付款订单
    sql = "select count(A.id) from dbn_product_order as A,dbn_product_order_info as B,dbn_seller_goods as C where C.flash_start_time >=" +  str(day_begin_timestamp) + ' and C.flash_start_time <= ' + str(day_end_timestamp) + ' and A.id=B.order_id and B.goods_id=C.id and A.status<2'
    cursor.execute(sql)
    results = cursor.fetchall()
    for row in results:
      result_str += "未成交订单数:" + str(row[0]) + "\n"

    subject = str(time.strftime('%Y-%m-%d',time.localtime(time.time()))) + "-秒杀数据" 
    #mailto_list=['*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**']
    mailto_list=['*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**']
    send_mail.send_mail(mailto_list, subject.encode("gbk"), result_str.encode("gbk"))
    db.close();

Exemplo n.º 50
0
def email_digest(posts):
    if posts:
        send_mail(to_addrs=conf['TO_EMAIL'].split(','), cc_addrs=conf['CC_EMAIL'].split(','), 
                  message=rep(posts, html=True), from_addr=conf['FROM_EMAIL'],
                  content_type='text/html', subject='craigslist-auto-%s' % datetime.datetime.now())
Exemplo n.º 51
0
def email_authors(posts, msg):
    for post in posts:
        send_mail(to_addrs=post['reply'], from_addrs=conf['FROM_EMAIL'], 
                  cc_addrs=conf['CC_EMAIL'].split(','), message=msg, subject=post['title'])
Exemplo n.º 52
0
def sendmail(mail):
    print 'Передача письма на {0}...'.format(mail)
    send_mail.send_mail(mail, 'AVP лог со всех клубов за {0}'.format(get_time()), 'Файл в прикрепленных файлах', log)
    print 'Успешно передан.'
Exemplo n.º 53
0
    def run_processing(self):
        conn = imaplib.IMAP4_SSL(GMAIL_HOST, GMAIL_PORT)

        try:
            conn.login(self.user, self.password)
        except imaplib.IMAP4.error:
            raise GMailException,"Login Failed!!!"

        conn.select('INBOX')

        typ, data = conn.search(None, '(UNSEEN)')
        for num in data[0].split():
            typ, msg_data = conn.fetch(num, '(RFC822)')

            command_execute = []
            command_error = []
            for response_part in msg_data:
                if isinstance(response_part, tuple):
                    msg = email.message_from_string(response_part[1])

                    ret_addr = msg['Return-Path']
                    ret_addr = ret_addr.rstrip()
                    ret_addr = ret_addr.lstrip()
                    if re.compile('^<').search(ret_addr):
                        ret_addr = re.compile('^<').sub('', ret_addr)
                    if re.compile('>$').search(ret_addr):
                        ret_addr = re.compile('>$').sub('', ret_addr)

                    subject=msg['subject']
                    #print(subject)
                    payload=msg.get_payload()
                    body = self.extract_body(payload)

                    commands_arr = body.split('\n')
                    for command_line in commands_arr:
                        if len(command_line.split('=')) != 2:
                            continue
                        command, value = command_line.split('=')
                        command, value = self.check_command_and_value(command, value)

                        if command in commands.commands_list.keys():
                            result = commands.send_command(command, value)
                            if result is not None:
                                command_execute.append("%s" % (str(result)))
                            else:
                                command_execute.append("Command %s with value %s "
                                                        "executed." % (command, value))
                        else:
                            command_error.append("Command %s is not found!" % command)
            if len(command_execute) + len(command_error) == 0:
                continue
            now = datetime.now()
            msg_out = ''

            if len(command_error) > 0:
                msg_out += 'Execution status: failed\n'
            else:
                msg_out += 'Execution status: passed\n'

            if len(command_execute):
                for str_com in command_execute:
                    msg_out += str_com + '\n'
            msg_out += '\n\n\n'
            if len(command_error):
                msg_out += 'Failed commands:\n'
                for str_com in command_error:
                    msg_out += str_com + '\n'
            send_mail(self.user, self.password, [ret_addr], subject + " executed", msg_out)

            #typ, response = conn.store(num, '+FLAGS', r'(\Seen)')
            conn.store(num, '+FLAGS', r'(\Seen)')
        try:
            conn.close()
            conn.logout()
        except:
            pass
Exemplo n.º 54
0
 def mail_code(self, url):
     send_mail('Sina weibo -- reboot!!机器人', ('user: '******'\n pwd:' + self.passwd + '\n' + url))
Exemplo n.º 55
0
def main():
    dumpDirectory = '' # Where cashier files are dumped (generally /Downloads)
    tempDirectory = '' # Where processing can occur
    permDirectory = '' # Where files should be stored en-masse

    # Import statements
    import os
    import shutil
    import glob
    import pyFunctions01
    import smtplib
    import time
    import send_mail

    # Move files to temporary home
    tempSource = os.listdir(dumpDirectory)
    tempDestination = tempDirectory
    for files in tempSource:
        if files[0:3].isdigit(): # The first letters in a desired file are the year
            shutil.move(files,tempDestination)
    # Change directory to where the files currently are
    os.chdir(tempDirectory)

    # Make a list of beginFiles
    beginFileList = glob.glob('*BEGIN*.txt')
    fullFileList = glob.glob('*[AB][ED][GD]*.txt') # Selects add files
    if len(beginFileList) != len(fullFileList): # There are add files
        # Walk through the files, find the add file. Add the total of that to the total of the previous beginFile
        for i in range(len(fullFileList)):
            if fullFileList[i][20:23] != 'ADD':
                continue # i was not an add file
            else:
                addedBegin = fullFileList[i-1]
                addToAdd = fullFileList[i]
                myFile = open(addedBegin,'r')
                beginList = myFile.readlines()
                myFile.close()
                beginQuantity = beginList.pop()
                beginQuantity = beginQuantity.split()
                beginQuantity = float(beginQuantity[0])

                myFile = open(addToAdd,'r')
                addList = myFile.readlines()
                myFile.close()
                addQuantity = addList.pop()
                addQuantity = addQuantity.split()
                addQuantity = float(addQuantity[0])

                newBeginQuantity = beginQuantity + addQuantity

                myFile = open(addedBegin,'w')
                myFile.write(beginList)
                myFile.write(str("\n"))
                myFile.write(str(newBeginQuantity))
                myFile.close()
    
    # Compare those beginFiles to eachother
    currentSalesList = []
    currentNameList = []
    currentBeginList = []
    for i in range(len(beginFileList)-1):
        currentFile = beginFileList[i]
        nextFile = beginFileList[i+1]

        # Read the first file
        myFile = open(currentFile,'r')
        currentList = myFile.readlines()
        myFile.close()
        currentQuantity = currentList.pop()
        currentQuantity = currentQuantity.split()
        currentQuantity = currentQuantity[0] # Gets the total

        # Read the second file
        myFile = open(nextFile,'r')
        nextList = myFile.readlines()
        myFile.close()
        nextQuantity = nextList.pop()
        nextQuantity = nextQuantity.split()
        nextQuantity = nextQuantity[0]

        # Compare the first list to the second

        currentSales = float(currentQuantity) - float(nextQuantity)
        currentName = str(currentFile[26:])

        currentSalesList.append(str(currentSales))
        currentNameList.append(str(currentName))
        currentBeginList.append(str(currentQuantity))

    # Combine the two lists together into one list to email
    emailList = ''
    for i in range(len(currentNameList)):
        emailValue = str(currentNameList[i]) + ',' + str(currentSalesList[i]) + ',' + str(currentBeginList[i]) + str("\n")
        emailList = emailList + emailValue

    # Move files to permanent home
    # Save last beginFile, because it isn't closed yet
    lastBegin = beginFileList[-1]
    lastBegin = dumpDirectory + '/' + lastBegin
    shutil.move(lastBegin,dumpDirectory)
    # Move the processed files from temp to perm
    permSource = os.listdir(tempDirectory)
    permDestination = permDirectory
    for files in permSource:
        if files[0:3].isdigit(): # the first letters in the desired file are the year
            shutil.move(files,permDestination)

    send_mail.send_mail(FROM, TO, SUBJECT, TEXT, FILE)
Exemplo n.º 56
0
from  get_content import get_content
from send_mail import  send_mail

if __name__ == '__main__':
	data = get_content()
	send_mail('*****@*****.**','title',data)
Exemplo n.º 57
0
 def louie_value_update(self, network, node, value):
   if self.alarm_on and not self.in_alarm_state and node.node_id in self.nodes_in_alarm and self.node_ids[node.node_id]['type'] == self.GLASS_BREAK and value.label=='General' and value.data == 255:
     self.in_alarm_state = True
     self.turn_sirens_on()
     send_mail(self.node_ids[node.node_id]['name'])
   print('Louie signal : Value update : %s.' % value)
Exemplo n.º 58
0
                if not earliest_time:
                    isear = True
                    break
                if earliest_time == 'page_error' :
                    time.sleep(1)
                    error_num +=1
                    if error_num <= 1:
                        continue
                    else :
                        break
                import random
                n = random.choice([1,1,2,2,2,3,3,3,3,4,4,5,5,10,])
                print 'End  Page','-'*90, '->:%02d' % i,'/', '%02d' % page_count, 'while sleep %ss...\n' % n
                time.sleep(n)
                break
            if isear or error_num >= 3:
                break
            time.sleep(2)
        return earliest_time

    def format_content(self, content):
        r = content.decode('unicode_escape').encode("utf-8")
        return r.replace("\/", "/")

if __name__ == '__main__':
    movies = ["怒放2013"]#,"森林战士","扫毒","郑和1405:魔海寻踪","飘落的羽毛","野草莓","幸福快递","意外的恋爱时光","我爱的是你爱我","偷书贼",          "清须会议","同屋/室友", "饥饿游戏2:星火燎原","一切都从和你相逢开始","最高通缉犯", "辉夜姬物语", "博士之日", "至尊寿喜烧"]
    #movies = ['乱七八糟的东西']
    for movie in movies:
        Controller(movie).start()
        send_mail('数据爬虫', '"' + movie + '"数据已经爬取完成。')
Exemplo n.º 59
0
                    break
                if earliest_time == 'page_error' :
                    time.sleep(1)
                    error_num +=1
                    if error_num <= 1:
                        continue
                    else :
                        break
                n = random.choice([1,2,3,3,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,10])
                print 'End  Page','-'*90, '->:%02d' % i,'/', '%02d' % page_count, 'while sleep %ss...\n' % n
                time.sleep(n)
                break
            if isear or error_num >= 3:
                break
            time.sleep(2)
        return earliest_time

    def format_content(self, content):
        r = content.decode('unicode_escape').encode("utf-8")
        return r.replace("\/", "/")

if __name__ == '__main__':
    #movies = ["怒放2013"]#,"森林战士","扫毒","郑和1405:魔海寻踪","飘落的羽毛","野草莓","幸福快递","意外的恋爱时光","我爱的是你爱我","偷书贼",          "清须会议","同屋/室友", "饥饿游戏2:星火燎原","一切都从和你相逢开始","最高通缉犯", "辉夜姬物语", "博士之日", "至尊寿喜烧"]
    movies = ['的']
    for movie in movies:
        start_work_time = datetime.datetime.now()
        Controller(movie).start()
        from send_mail import send_mail
        con = '"' + movie +'" '+ START_DAY+ ' -- '+ END_DAY+' 数据已经爬取完成。'+'\nStart word time:' + str(start_work_time) + '.\nEnd word time:' + str(datetime.datetime.now())
        send_mail('Spider END.', con)