Example #1
0
def create_account(user, password, email):
    salt = urandom(16).encode('hex')
    verify = urandom(16).encode('hex')
    hashPwd = sha512(password + salt).hexdigest()
    if email is not None:
        send_email.send(email, user, verify, "Signup")
        userColl.insert({
            '_id': user,
            'salt': salt,
            'pass': hashPwd,
            'email': email,
            'signup_date': datetime.utcnow(),
            'signup_ip': request.remote_addr,
            'reset_ip': '',
            'verified': verify,
            'last_login': datetime.utcnow()
        })
    else:
        userColl.update({'_id': user}, {
            "$set": {
                'salt': salt,
                'pass': hashPwd,
                'reset_ip': request.remote_addr,
                'last_login': datetime.utcnow()
            }
        })
    if userColl.find_one({'_id': user})['verified'] == True:
        session['username'] = user
Example #2
0
    def accept(org_uuid):
        try:
            org_data = Organization.fetchByUUID(org_uuid)

            # Check their status
            if org_data[3] == 2:
                raise OrgException("Organization already accepted!")
            else:
                send_email.send(
                    'Application Accepted',
                    f'Hi {org_data[2].strip()}!\n\n\nWe are pleased to inform you that your application ({org_data[1]}) for being an organization registered with us has been accepted. You can now log in to the application and begin accepting donations.\n\nRegards,\nDonation Nation',
                    [
                        org_data[12],
                    ])
                dbcon = sql.connect()
                cur = dbcon.cursor()
                cur.execute("UPDATE organizations SET status=2 WHERE UUID=?",
                            (org_data[1], ))
                cur.close()
                dbcon.commit()
                dbcon.close()
        except OrgException as e:
            raise e
        except Exception as e:
            traceback.print_exc()
            raise e
Example #3
0
 def addItem(form, session, files):
     if check_form(form, [
             'name', 'category', 'condition', 'description', 'organization',
             'time'
     ]) and 'image' in files:
         item_uuid = str(uuid.uuid4())
         user_uuid = session['isLoggedIn'][1]
         current_time = datetime.now().strftime("%d/%m/%Y - %H:%M:%S")
         image = standard_b64encode(files['image'].read())
         try:
             org = Organization.fetchByUUID(form['organization'])
             send_email.send(
                 'New Item Offered!',
                 f'Hi {org[2].strip()}!\n\n\nYou have been offered a new item ({form["name"]}) [{form["category"]}]! Log into the application to approve or reject this item!\n\nRegards,\nDonation Nation',
                 [
                     org[12],
                 ])
             dbcon = sql.connect()
             cur = dbcon.cursor()
             cur.execute(
                 "INSERT INTO items (UUID,item_name,category,condition,description,org_id,user_id,time_submitted,pickup_time,image,status) VALUES (?,?,?,?,?,?,?,?,?,?,0)",
                 (item_uuid, form['name'], form['category'],
                  form['condition'], form['description'],
                  form['organization'], user_uuid, current_time,
                  form['time'], image))
             dbcon.commit()
             cur.close()
             dbcon.close()
         except Exception as e:
             # We raise any exception so that the flask app can handle it
             traceback.print_exc()
             raise UserException('Something went wrong. Contact an admin.')
     else:
         raise UserException('Missing or invalid information!')
Example #4
0
 def reject(org_uuid):
     try:
         org_data = Organization.fetchByUUID(org_uuid)
         # Check their status
         if org_data[3] == 2:
             raise OrgException("Organization already accepted!")
         else:
             send_email.send(
                 'Application Rejected',
                 f'Hi {org_data[2].strip()}!\n\n\nWe regret to inform you that your application ({org_data[1]}) for being an organization registered with us has been rejected. You can contact us at [email protected] to repeal your rejection.\n\nRegards,\nDonation Nation',
                 [
                     org_data[12],
                 ])
             dbcon = sql.connect()
             cur = dbcon.cursor()
             cur.execute("DELETE FROM organizations WHERE UUID=?",
                         (org_data[1], ))
             cur.fetchone()
             cur.close()
             dbcon.commit()
             dbcon.close()
     except OrgException as e:
         raise e
     except Exception as e:
         traceback.print_exc()
         raise e
Example #5
0
def update_database_code(login, cur, db):
	random_code = randint(100000, 999999)
	cur.execute("UPDATE `USERS` SET `1time_code`=%s WHERE `Login`=%s", [random_code, login])
	db.commit()
	# SEND SMS
	send_email.send(login, random_code)

	return 0
Example #6
0
 def emit(self, record):
     "Invia messaggio di log via GMail"
     try:
         sm.send("", None, self.fromaddr, self.dest, self.subject,
                 self.format(record))
     except Exception as excp:
         _last_resort_log("Errore invio email a: %s\n- %s" %
                          (self.dest, str(excp)))
Example #7
0
def index():

    # Read Sensors Status
    buttonSts = GPIO.input(button)
    senPIRSts = GPIO.input(senPIR)
    ledlightSts = GPIO.input(light)

    if senPIRSts == 0:  #When output from motion sensor is LOW
        message = "No intruders"
        GPIO.output(light, 0)  #Turn OFF LED

    elif senPIRSts == 1:

        #When output from motion sensor is HIGH
        now = datetime.now()
        dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
        message = "Intruder detected on " + dt_string
        start_time = time.time()

        while True:

            buttonSts = GPIO.input(button)
            mode = request.args.get('mode')
            print("The mode now is", mode, start_time)
            #print(request.args);

            if mode == '1':
                print("changing button")
                buttonSts = False

            if buttonSts == False:
                message = "False Alarm! No Intruder"
                GPIO.output(light, False)  #turn off
                break

            #if a min has passed without the safe button being pressed send an email
            elif buttonSts == True and (time.time() - start_time > 60):
                message = "One minute has passed owner alerted via Email"
                send_email.send()
                break

            else:

                GPIO.output(light, True)  #light on
                time.sleep(0.4)  #Time delay

                GPIO.output(light, False)  #light off
                time.sleep(0.4)

    templateData = {
        'title': 'Security System!',
        'button': buttonSts,
        'senPIR': senPIRSts,
        'light': ledlightSts,
        'message': message
    }

    return render_template('index.html', **templateData)
Example #8
0
def monitor():
    #获取本机IP
    localIp = os.popen(Settings["getIp_command"]).read().strip()
    print '本机IP:',localIp
    #查找目标进程
    monitor_ports = '|'.join(Settings["server_dict"].keys())
    print '需要监控的端口:',monitor_ports
    #循环检查
    p_command = Settings["getProcess_command"] % (localIp,monitor_ports)
    # print '查找目标进程命令:',p_command
    services = []
    # 拼接校验url
    for port in Settings["server_dict"].keys():
        services.append(localIp + ':' +port + '\n')
    # print '期望存在服务:',services
    while True:
        host_ports = os.popen(p_command).readlines()
        print '找到进程:',host_ports
        # 如果目标服务数量已不足期望,检查是哪个服务挂了
        if len(host_ports) < len(Settings["server_dict"].keys()):
            # 获取期望存在服务与实际存在服务之间的差集
            diffs = list(set(services).difference(set(host_ports)))
            # 发送告警短信与邮件
            for diff in diffs:
                # 替换发短信命令的占位符
                module_name = Settings['profile'] + '-' + Settings["server_dict"][diff.strip().split(':')[1]]
                command = Settings["sendMsg_commad"] % (Settings["alarm_phones"],module_name,'进程已终止')
                if diff not in Alarm_cache["dead_process"]:
                    print diff.strip(),'服务挂了,发送短信提醒'
                    #发短信
                    os.system(command)
                    #发邮件
                    send_email.send("【"+module_name +"】异常","进程已终止,赶快修复")
                    Alarm_cache["dead_process"].append(diff) #加入缓存 避免大量重复报警

        else:
            print '进程没挂,继续检查心跳'
            Alarm_cache['dead_process'] = []
        # 给服务发送心跳
        for host_port in host_ports:
            host_port = host_port.strip()
            ping_url = "http://"+host_port+"/api/ping"
            command = Settings["pingPong_command"] + ping_url
            http_status = os.popen(command).read()
            print 'ping:',ping_url,'状态码:',http_status
            if http_status != '200':
                if diff not in Alarm_cache["ping_error"]:
                    print '心跳检查异常,发送报警短信:',Settings["alarm_phones"]
                    module_name = Settings['profile'] + '-' +Settings["server_dict"][host_port.strip().split(':')[1]]
                    #发短信
                    os.system(Settings["sendMsg_commad"] % (Settings["alarm_phones"],module_name,'心跳不通,服务可能是挂了'))
                    #发邮件
                    send_email.send("【"+module_name +"】异常","心跳不通,服务可能是挂了")
                    Alarm_cache["ping_error"].append(diff) #加入缓存 避免大量重复报警
        print '一分钟后再次检查'
        time.sleep(60)
Example #9
0
def main_core():
    ser.readline()
    while True:
        pomiars = []
        pomiars.append(get_data_serial())
        pomiars.append(get_data_serial())
        write_to_file(pomiars)
        send_email.send(file_name)
        os.remove(file_name)
        time.sleep(1)
Example #10
0
def check(sitetype, dict, attach_img=None, to=[], cc=[], bcc=[]):

    if attach_img != None:
        return send_email.send(sitetype, dict, attach_img)
    if str(dict) == "{}":
        return sitetype + "\n"
    elif str(dict) == "[]":
        return sitetype + "\n"
    else:
        return send_email.send(sitetype, dict, attach_img)
Example #11
0
def main_core ():
    while True:
        pomiars = []
        pomiars.append(get_data_serial ())
        pomiars.append(get_data_serial ())
        pomiars.append(get_data_serial ())
        #pomiars.append(get_data_serial ())
        write_to_file (pomiars)
        send_email.send ()
        os.remove ('zapis.txt')
        time.sleep (1)
Example #12
0
def detected_callback():
    snowboydecoder.play_audio_file()
    try:
        capture()
    except:
        print "Error when capturing images"
    try:
        send()
    except:
        print "Error when sending emails"
    print("Continue listening... Press Ctrl+C to exit")
Example #13
0
def run():
    # 执行全部爬虫,将爬取到的信息进行对人友好的处理(可能是html?)
    ret = []
    for _ in _spiders:
        cur_s = _()
        per_ret = cur_s.start()
        for k, v in per_ret.items():
            ret.append(k + ':' + v)
    ret = "\n".join(ret)
    # 将结构化数据发送到邮箱
    send(ret)
Example #14
0
def lambda_handler(event, context):

    # 現在時刻を取得
    JST = timezone(timedelta(hours=+9), 'JST')
    time = datetime.now(JST).strftime('%Y年%-m月%-d日 %-H時%-M分')

    # htmlメールテンプレート読み込み
    html_template = open("./mail.html", "r").read()

    # テーブル名を指定
    table_name = "hackathon-mobilehub-342417472-messages"

    # DynamoDBテーブルのオブジェクトを取得
    dynamotable = dynamodb.Table(table_name)

    # 件数取得
    table_json = dynamotable.scan()['Items']
    record_num = len(dynamotable.scan()['Items'])

    # 登録されている友達の数だけ繰り返す
    for i in range(0, record_num):

        # 遺影のURL
        yeah_url = 'https://dtills38xd8p8.cloudfront.net/uploads/yeah_grayscale/' + table_json[i]['userId'] + '.jpg'

        # 遺言メッセージ
        message = table_json[i]['message']

        # 遺言動画のURL
        movie_url = 'https://dtills38xd8p8.cloudfront.net/uploads/movies/' + table_json[i]['movie']

        print(movie_url)

        # html 文字列置換
        html = html_template
        html = html.replace('_senderName', table_json[i]['senderName'])
        html = html.replace('_yeahURL', yeah_url)
        html = html.replace('_lastDate', time)
        html = html.replace('_message', message)
        html = html.replace('_movieURL', movie_url)

        # Email 送信
        email.send(table_json[i]['sender'], table_json[i]['receiver'], table_json[i]['senderName'], message, html)

    result = {
        "isBase64Encoded" : True,
        "statusCode": 200,
        "headers": { 'Content-Type': 'application/json' },
        "body": "JSON string"
    }

    return result
Example #15
0
def insertNewstoDB():
    mysql_s = database.Mysql()
    data=getTopNewsimg()
    send_email.send(str(data).replace('u\'', '\'').decode("unicode-escape"))
    for news in data:
        print(news)
        mydict={}
        mydict['title']=news[1]
        mydict['content'] = news[4]
        mydict['url'] = news[2]
        mydict['image_url'] = news[3]
        print(mydict)
        mysql_s.insertData("tb_news",mydict)
Example #16
0
    def insert(form, files):
        if check_form(form, [
                'name', 'registrationNumber', 'city', 'emirate', 'POBox',
                'address1', 'address2', 'phone', 'email', 'password',
                'confirmPassword'
        ]) and (files['logo'] is not None):
            is_all_alpha(form, ['name', 'city', 'emirate'])
            is_all_alnum(form, ['POBox'])
            is_all_numeric(form, ['phone', 'registrationNumber'])
            is_email(form, 'email')
            Organization.check_phone_exists(form['phone'])
            Organization.check_email_exists(form['email'])
            hash = ''
            logo = standard_b64encode(files['logo'].read())
            if form['password'] != form['confirmPassword']:
                raise OrgException('Both password fields must be the same.')
            else:
                hash = hashlib.sha256(
                    form['password'].encode('utf-8')).hexdigest()
                org_uuid = str(uuid.uuid4())
            try:
                dbcon = sql.connect()
                dbcon.execute(
                    "INSERT INTO organizations (UUID, name, status, license_no, city, emirate, po_box, address_1, address_2, phone, logo, email, password) VALUES (?,?,0,?,?,?,?,?,?,?,?,?,?)",
                    (org_uuid, form['name'], form['registrationNumber'],
                     form['city'], form['emirate'], form['POBox'],
                     form['address1'], form['address2'], form['phone'], logo,
                     form['email'], hash))
                verification_uuid = str(uuid.uuid4())
                dbcon.execute("INSERT INTO verifications VALUES (?,?)",
                              (org_uuid, verification_uuid))

                # Send email to user for verification
                send_email.send(
                    'Email Verification',
                    f'Hi {form["name"].strip()}!\n\n\nThank you for signing up for Donation Nation!\n\nTo complete your registration and enable your account, please verify your email by visiting the link: http://127.0.0.1:5000/verify_org/{verification_uuid}\n\nRegards,\nDonation Nation',
                    [
                        form['email'],
                    ])

                # Commit changes and close the db connection
                dbcon.commit()
                dbcon.close()
            except Exception:
                traceback.print_exc()
                raise OrgException("Something went wrong. Contact an admin.")
        else:
            raise OrgException("Invalid or missing information!")
Example #17
0
def go():

    #===================================================#
    #메일에 들어갈 내용
    mail_body = {}
    abort_date = "N"
    abort_thing = "N"
    abort_why = "N"

    #오늘날짜
    today = datetime.datetime.now()
    #===================================================#

    driver = webdriver.Chrome()
    driver.get("https://www.safedriving.or.kr/main.do")

    #화면 최대화
    driver.maximize_window()

    #스크린샷
    filename = os.getcwd() + "/todayscreen" + ".png"
    shot = driver.get_screenshot_as_file(filename)

    #MIMEImage로 변환
    fp = open(filename, 'rb')
    context = fp.read()
    img = MIMEImage(context)
    context = str(context)
    fp.close()

    is_write = True
    #이전 시간에 보냈는지 확인
    with open('safedriving.txt', mode='a+', encoding='utf8') as title_file:
        title_file.seek(0)
        templine = title_file.read()
        #파일에 내용이 없으면 False
        if not templine:
            is_write = False
        #기존에 읽었으면 True
        if (context == templine):
            is_write = True

    if is_write is False:
        with open('safedriving.txt', mode='w', encoding='utf8') as title_file:
            title_file.write(context)
        send_email.send("도로교통공단 안전운전 통합민원", dict=[], attach_img=img)

    driver.quit()
Example #18
0
    def insert(form):
        # Check that all information is here
        if check_form(form, [
                'firstName', 'lastName', 'dob', 'city', 'emirate', 'POBox',
                'address1', 'address2', 'phone', 'email', 'password',
                'confirmPassword'
        ]):
            is_all_alpha(form, ['firstName', 'lastName', 'city', 'emirate'])
            is_all_alnum(form, ['POBox'])
            is_all_numeric(form, ['phone'])
            is_email(form, 'email')
            User.check_phone_exists(form['phone'])
            User.check_email_exists(form['email'])
            hash = ''
            if form['password'] != form['confirmPassword']:
                raise UserException('Both password fields must be the same.')
            else:
                hash = hashlib.sha256(
                    form['password'].encode('utf-8')).hexdigest()
                user_uuid = str(uuid.uuid4())
            try:
                dbcon = sql.connect()
                dbcon.execute(
                    "INSERT INTO users (UUID, first_name, last_name, dob, city, emirate, po_box, address_1, address_2, phone, email, password, isAdmin, isVerified) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,0,0)",
                    (user_uuid, form['firstName'], form['lastName'],
                     form['dob'], form['city'], form['emirate'], form['POBox'],
                     form['address1'], form['address2'], form['phone'],
                     form['email'], hash))
                verification_uuid = str(uuid.uuid4())
                dbcon.execute("INSERT INTO verifications VALUES (?,?)",
                              (user_uuid, verification_uuid))

                # Send email to user for verification
                send_email.send(
                    'Email Verification',
                    f'Hi {form["firstName"].strip()}!\n\n\nThank you for signing up for Donation Nation!\n\nTo complete your registration and enable your account, please verify your email by visiting the link: http://127.0.0.1:5000/verify_user/{verification_uuid}\n\nRegards,\nDonation Nation',
                    [
                        form['email'],
                    ])

                # Commit changes and close the db connection
                dbcon.commit()
                dbcon.close()
            except Exception:
                traceback.print_exc()
                raise UserException("Something went wrong. Contact an admin.")
        else:
            raise UserException("Invalid or missing information!")
Example #19
0
def success():
   if request.method=='POST':
      email = request.form["email_name"]
      height = request.form["height_name"]
      if db.session.query(Data).filter(Data.email_==email).count() == 0:
         data = Data(email, height)
         db.session.add(data)
         db.session.commit()

         average = db.session.query(func.avg(Data.height_)).scalar()
         average = round(average, 1)
         count = db.session.query(Data.height_).count()
         send(email, height, average, count)
         return render_template("success.html")
      else:
         # return render_template("index.html")
         flash("Seems like your email is already registered !!!", "info")
         return redirect(url_for("index"))
Example #20
0
def maybe_send_alert(wells):
    ok = True
    badwells = []
    wellnames = ["north", "west", "front", "furnace", "store"]
    for wellname,well in zip(wellnames, wells):
        if well == 0:
            ok = False
            badwells.append(wellname)

    if not ok:
        if len(recent_alerts()) > 3:
            return
        else:
            log_alert()
            msg = "The following wells are overfull: %s\n" % (", ".join(badwells))
            msg += "The time is: %s\n" % (arrow.now().format("YYYY/MM/DD HH:mm:ss"))
            for addr in ALERT_ADDRS:
                send_email.send(addr, "WELL ALERT", msg)
Example #21
0
def getTopImages():#只得到无图片型资讯
    reload(sys)
    list=[]
    sys.setdefaultencoding("gbk")
    url="http://www.umei.cc/bizhitupian/fengjingbizhi/"
    images=[]
    i=1
    # csvfile=open("D:csv_top_images.csv","wb")
    # writer=csv.writer(csvfile)
    # writer.writerow(('ID',u'图片标题',u'图片链接地址',u'图片网址'))
    getImage(url, i)
    for page in range(2,4):
        i+=1
        url = "http://www.umei.cc/bizhitupian/fengjingbizhi/"
        print("正在解析第"+str(page)+"页新闻数据")
        url=url+str(page)+".htm"
        print(url)
        images=getImage(url,i)
        list.append(images)
        insertImagedb(images)
        send_email.send(str(list).replace('u\'','\'').decode("unicode-escape"))
Example #22
0
def send_email(mailhost, sender, recipients, subj, body, debug_addr=''):  # pylint: disable=R0913
    "Invio messaggio e-mail"
    if debug_addr:
        warning = "MODO DEBUG - destinatari originali: %s\n\n" % ', '.join(
            recipients)
        message = warning + body
        dest = [debug_addr]
        subjd = subj + ' (DEBUG)'
    else:
        message = body
        dest = recipients
        subjd = subj
    if mailhost.strip() == "-":
        mailhost = None
    try:
        sm.send(mailhost, None, sender, dest, subjd, message)
    except Exception as excp:
        errmsg = "Mail to: %s - " % ', '.join(recipients) + str(excp)
        logging.error(errmsg)
        return False
    return True
def main():
    dirname = os.path.dirname(__file__)
    filename = os.path.join(dirname, '../database/source/red.jpg')
    filename = os.path.normpath(filename)
    red = cv2.imread(filename)
    filename = os.path.join(dirname, '../database/source/green.jpg')
    filename = os.path.normpath(filename)
    green = cv2.imread(filename)
    d = prepare.load_db()

    while True:
        img = green
        cv2.imshow('green light', img)
        cv2.waitKey(5000)
        cv2.destroyWindow('green light')

        img = red
        cv2.imshow('red light', img)
        cv2.waitKey(2000)
        cv2.destroyWindow('red light')

        video_capture = cv2.VideoCapture(0)
        ids = recognition.recognition(video_capture, d.copy())

        for i in range(0, len(d["ids"])):
            for id_person in ids:
                if id_person != -1:
                    if d["ids"][i] == id_person:
                        filename = os.path.join(
                            dirname, '../database/recognized_faces/' +
                            str(id_person) + '.jpeg')
                        filename = os.path.normpath(filename)
                        send_email.send(d["emails"][i], d["full_names"][i],
                                        filename)

        video_capture.release()
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    cv2.destroyAllWindows()
Example #24
0
 def accept(uuid):
     try:
         item_data = User.fetchItemByUUID(uuid)
         org_data = Organization.fetchByUUID(item_data[6])
         send_email.send(
             'Item Accepted',
             f'Hi {org_data[2]}!\n\n\nThe item ({item_data[2]}) [UUID: {item_data[1]}] has been accepted by the user for pickup. Contact the user for further details.\n\nRegards,\nDonation Nation',
             [
                 org_data[12],
             ])
         dbcon = sql.connect()
         cur = dbcon.cursor()
         cur.execute('UPDATE items SET status=? WHERE UUID=?', (1, uuid))
         dbcon.commit()
         cur.close()
         dbcon.close()
     except UserException as ue:
         raise ue
     except Exception:
         traceback.print_exc()
         raise UserException(
             'An issue has occurred. Please contact an admin.')
Example #25
0
 def acceptItem(uuid):
     try:
         item_data = User.fetchItemByUUID(uuid)
         user_data = User.fetchByUUID(item_data[7])
         send_email.send(
             'Item Accepted',
             f'Hi {user_data[2]}!\n\n\nYour item ({item_data[2]}) [UUID: {item_data[1]}] has been accepted for pickup. The organization you donated to should contact you shortly.\n\nRegards,\nDonation Nation',
             [
                 user_data[11],
             ])
         dbcon = sql.connect()
         cur = dbcon.cursor()
         cur.execute('UPDATE items SET status=? WHERE UUID=?', (1, uuid))
         dbcon.commit()
         cur.close()
         dbcon.close()
     except OrgException as ue:
         raise ue
     except Exception:
         traceback.print_exc()
         raise OrgException(
             'An issue has occurred. Please contact an admin.')
Example #26
0
 def removeItem(uuid):
     try:
         item_data = User.fetchItemByUUID(uuid)
         user_data = User.fetchByUUID(item_data[7])
         send_email.send(
             'Item Rejected',
             f'Hi {user_data[2]}!\n\n\nYour item ({item_data[2]}) [UUID: {item_data[1]}] has been rejected by the organization. Either try again or contact the organization for more details.\n\nRegards,\nDonation Nation',
             [
                 user_data[11],
             ])
         dbcon = sql.connect()
         cur = dbcon.cursor()
         cur.execute('UPDATE items SET status=-1 WHERE UUID=?', (uuid, ))
         dbcon.commit()
         cur.close()
         dbcon.close()
     except OrgException as ue:
         raise ue
     except Exception:
         traceback.print_exc()
         raise OrgException(
             'An issue has occurred. Please contact an admin.')
def main(invoice_ref, opts):

    include = []
    if opts.include:
        include = csv_as_list(opts.include)

    exclude = []
    if opts.exclude:
        exclude = csv_as_list(opts.exclude)

    split_code = []
    if opts.split_code:
        split_code = csv_as_list(opts.split_code)

    only_admin = []
    if opts.only_admin:
        only_admin = csv_as_list(opts.only_admin)

    recipients = make_invoices(invoice_ref, split_code, include, exclude,
                               only_admin)
    if recipients:
        send_email.send(recipients, invoice_ref)
Example #28
0
 def set():
     user_email = askstring("Email", "Enter your email :")
     try:
         if len(user_email) > 2 and user_email.count(
                 "@") == 1 and user_email.count(
                     ".") >= 1:  # Send if it is a valid email address
             image.save(screen.subsurface(rects["canvas"]),
                        "local/saves/email%d.png" % saved)
             send(user_email, "Your masterpiece is ready!",
                  "Thanks for using Ubuntu Splash 2.0",
                  "email%d.png" % saved)
             messagebox.showinfo(
                 title="Email Sent",
                 message="Email sent successfully!\nEvent logged to file.")
         else:
             f = open("local/events.log",
                      "a")  # Log to events file without overwrite
             f.write("Invalid email entered. Email not sent \n")
             f.close()
     except:
         messagebox.showinfo(
             title="Email Not Sent",
             message="Email not sent successfully!\nEvent logged to file.")
Example #29
0
def test(hostname):
    max_tries = 3
    response = ping_with_retries(hostname, max_tries)
    if response is True:
        return
    humantime1, humantime2, epochtime2 = response
    last_email_time = 0
    try:
        with open(last_email_time_file, 'rb') as f:
            last_email_time = float(f.read().strip())
    except IOError:
        with open(last_email_time_file, 'wb') as f:
            f.write('0')
    if epochtime2 - last_email_time > DELAY_TIME:
        message = open('message.txt', 'rb').read().strip()
        message = message.format(max_tries, humantime1, humantime2)
        send_email.send(
                FROM_ADDRESS,
                TO_ADDRESSES,
                'Ping to %s failed' % hostname,
                message)
        with open(last_email_time_file, 'wb') as f:
            f.write(str(epochtime2))
Example #30
0
 def changePickupTime(form, uuid):
     try:
         item_data = User.fetchItemByUUID(uuid)
         org_data = Organization.fetchByUUID(item_data[6])
         send_email.send(
             'Item Pickup Date Changed',
             f'Hi {org_data[2]}!\n\n\nThe item ({item_data[2]}) [UUID: {item_data[1]}] has been suggested a new pickup time by the donator. Log in to the application to view and accept or reject the new pickup time.\n\nRegards,\nDonation Nation',
             [
                 org_data[12],
             ])
         dbcon = sql.connect()
         cur = dbcon.cursor()
         cur.execute(
             'UPDATE items SET pickup_time=?, status=? WHERE UUID=?',
             (form['time'], 3, uuid))
         dbcon.commit()
         cur.close()
         dbcon.close()
     except UserException as ue:
         raise ue
     except Exception:
         traceback.print_exc()
         raise UserException(
             'An issue has occurred. Please contact an admin.')
Example #31
0
def forgot_pw():
    if request.method == 'GET':
        return render_template('forgotpw.html')
    email = escape(request.form.get('email'))
    if userColl.find({
            'email': email
    }).count() == 0:  #checks if user with specified email exists
        return render_template('forgotpw.html',
                               email_error="Can't find that email")
    user = userColl.find_one({'email': email})['_id']
    if resetColl.find({
            'user': user
    }).count(
    ) != 0:  #checks if pending reset already exists, if yes marks it as invalid
        resetColl.remove({'user': user})
    resetID = urandom(16).encode('hex')
    resetColl.insert({
        '_id': resetID,
        'timestamp': datetime.utcnow(),
        'user': user
    })
    # webbrowser.get('open -a /Applications/Google\ Chrome.app %s').open_new_tab('http://127.0.0.1:5000/resetpw/'+resetID)
    send_email.send(email, user, resetID)
    return """
Example #32
0
 def changePickupTime(form, uuid):
     try:
         item_data = User.fetchItemByUUID(uuid)
         user_data = User.fetchByUUID(item_data[7])
         send_email.send(
             'Item Pickup Time Changed',
             f'Hi {user_data[2]}!\n\n\nYour item ({item_data[2]}) [UUID: {item_data[1]}] has been suggested a new pickup time. Log into the application to approve or reject this new time.\n\nRegards,\nDonation Nation',
             [
                 user_data[11],
             ])
         dbcon = sql.connect()
         cur = dbcon.cursor()
         cur.execute(
             'UPDATE items SET pickup_time=?, status=? WHERE UUID=?',
             (form['time'], 2, uuid))
         dbcon.commit()
         cur.close()
         dbcon.close()
     except OrgException as ue:
         raise ue
     except Exception:
         traceback.print_exc()
         raise OrgException(
             'An issue has occurred. Please contact an admin.')
Example #33
0
import send_email

send_email.send('testing')
Example #34
0
def oof(cf,plconf,date=False,last_date=False,FA='a',env=False):
  # start email notifications service:
  emailInfo=opt.email_info(cf=cf)
  sendEmail=emailInfo['send']
  #if sendEmail: sys.stdout=opt.Redirect()

  env_vars(env)
  flags=opt.flags_info(cf)

  if date: date=dateu.parse_date(date)
  if last_date: last_date=dateu.parse_date(last_date)

  if not date:
    # find date-1 for prediction:
    date,file=find_last(type='rst',cf=cf)
    if not date:
      on_error(sendEmail,'ERROR (%s): Cannot find previous file'%FA,emailInfo)
      return
    else:
      print 'Last date = %s from file %s' % (date,file)
      rout=opt.nameof('out','rout',date=date,FA='a',cf=cf)
      if is_roms_out_ok(rout):
        print 'Previous roms out is ok: %s' % rout
      else:
        on_error(sendEmail,'ERROR (%s): Last run is not ok %s : %s' % (FA,date,rout),emailInfo)
        return

  else:
    date=dateu.next_date(date,-1)

  # read dates:
  start_date,end_date=opt.dates_info(cf)
  if last_date: end_date=dateu.next_date(last_date,+1)

  while date >= start_date and date < end_date:

    # read dates again, possible update may occur.
    start_date,end_date=opt.dates_info(cf)
    if last_date: end_date=dateu.next_date(last_date,+1)

    date=dateu.next_date(date)

    # check if already runned for that date:
    # ie, check for rst and check if roms_out is ok:
    rst=opt.nameof('out','rst',date=date,FA=FA,cf=cf)
    rout=opt.nameof('out','rout',date=date,FA=FA,cf=cf)

    if os.path.isfile(rst):
      print 'Found rst file for %s: %s' % (date,rst)
      if os.path.isfile(rout):
        if is_roms_out_ok(rout):
          print '  previous roms out is ok: %s' % rout
        else:
          on_error(sendEmail,'ERROR (%s): Previous roms out is NOT ok: %s' % (FA,rout),emailInfo)
          break
      else:
        print '  roms out for %s not found: NOT CHECKED' % date

    else:

      print '\nModel will start from %s' % date

      # check for atm data for current simulation:
      if flags['atmfrc'] or flags['atmblk']:
        atmStat=check_atm(date,FA,cf=cf)
      else: atmStat=True

      ## wait for rst in case of fa==F:
      ##if FA=='f': rstStat=check_rst(date,cf=cf)
      ##else: rstStat=True
      rstStat=check_rst(date,cf=cf)

      # check for bondary data for current simulation:
      if flags['clmbry']:
        # this step may take forever !! just let us belive parent model is available
        #bcStat=check_bc(date,FA,cf=cf)
        bcStat=True
      else: bcStat=True

      now=time.strftime("%Y-%m-%d %H:%M:%S +0",time.gmtime())
      if (not atmStat is False) and (not rstStat is False) and (not bcStat is False):
        rout,dt,runErr=run(date,FA,cf=cf)
        now=time.strftime("%Y-%m-%d %H:%M:%S +0",time.gmtime())

        # check if run was ok:
        if is_roms_out_ok(rout):
          msg='NO error %s %s'%(date,FA)
          Msg='  Run %s %s finished ok [%s] dt=%6.2f' % (date,FA,now,dt)
          print Msg

          # make plots:
          if flags['plots']:
            err,savenames=op_plot.op_plt(cf,plconf,date,FA)
            if not all(e=='' for e in err):
              msg+=' --> ERROR plotting'
              print '  ERROR plotting : ',
              for e in err: print e

            if not all(e=='' for e in savenames):
              for sv in savenames:
                print '  Saved plot  '+sv

        elif runErr:
          on_error(sendEmail,'ERROR (%s): Run %s returned the error msg: %s' % (FA,date,runErr),emailInfo)
          break
        else:
          on_error(sendEmail,'ERROR (%s): Run %s finished with ERROR [%s] dt=%6.2f' % (FA,date,now,dt),emailInfo)
          break

      elif atmStat is False:
          Msg='ERROR (%s): Run %s cannot run (atm data missing) ERROR [%s]' % (FA,date,FA,now)
          if FA=='a':
            on_error(sendEmail,Msg,emailInfo)
            break
          else:
            msg='ERROR: atm data missing'
            print Msg

      elif rstStat is False:
        msg='ERROR: rst data missing'
        Msg='ERROR (%s): Run %s cannot run (atm data missing) ERROR [%s]' % (FA,date,now)
        print Msg


      print '\n'
      if sendEmail: send_email.send(emailInfo['dest'],Msg,msg)
Example #35
0
def on_error(sendEmail,err,emailInfo=False):
  print err
  msg='Op model STOP'
  print msg+'\n'
  if sendEmail: send_email.send(emailInfo['dest'],err,msg)#sys.stdout.content,err)
Example #36
0
    ftp=FTP(ftpserver)
    ftp.login(ftpuser, ftppassword)
except:
    print("Could not connect to the ftp server. Check server address, login and password")
try:
    ftp.cwd(basedir)
except:
    print("Could not change directory to "+basedir)
bad_tt=""
list_of_files = ftp.nlst()
for folder in list_of_files:
    if (folder=='.') or (folder=='..'):
        continue;
    try:
        ftp.cwd(folder+"/E")
        if (len(ftp.nlst())>2):
            bad_tt=bad_tt+"TT"+folder+" "
        ftp.cwd(basedir)
    except:
        print("Couldn't find folder "+folder+"/I in the current directory")
message =""
if bad_tt=="":
    message = "All clients was updated correctly! Yea!"
else:
    message = "We have some problems with clients: "+bad_tt
#message.encode('ascii', 'ignore').decode('ascii')
    #message=repr(message.encode("ascii"))
for email in email_addresses:
    send(email_sender, email_sender_passwd, email, "Check price update for DTRetail clients.", message)
ftp.close()
Example #37
0
def send_alert(alert_msg):
    send_email.send(alert_msg)
Example #38
0
    return entities_rank

#-------------------------------------------------------------------------------

if __name__ == "__main__":

    #sessionID = 'Trump2016-020'
    #wikipage = 'Donald_Trump_presidential_campaign,_2016'

    sessionID = 'Bernie2016-002'
    wikipage = 'Bernie_Sanders_presidential_campaign,_2016'
    #wikipage = 'United_States_presidential_election,_2016'

    # get hashtag from sessionID
    hashtag = sessionID[:-4]

    vars_dict = {"wikipage": wikipage, 'hashtag': hashtag}

    thread.start_new_thread(stream_tweets.getTweets, (vars_dict['hashtag'],))

    # Find the cooc hashtags every 6 minutes and save to DB
    while execute:

        time.sleep(6*60)

        try:
            findCoocHashtags(vars_dict, sessionID)
        except Exception as e:
            send_email.send("streamer error", str(e))
Example #39
0
def check_if_running(script_name):
	running  = subprocess.check_output(['ps', '-aux'])
	if script_name not in running:
		send_email.send('*****@*****.**', 'kippli2684!', '*****@*****.**', 'Monitoring script has stopped running!', 'Monitoring Script Not Running!')
		time.sleep(600)