Example #1
0
def Registration():
    msg = ''
    if request.method == "POST":
        name = request.form["name"]
        email = request.form["email"]
        password = request.form["password"]
        cursor = mysql.connection.cursor()
        cursor.execute('SELECT * FROM tableone WHERE name = % s', (name, ))
        account = cursor.fetchone()
        print(account)
        if account:
            msg = 'Account already exists !'
        elif not re.match(r'[^@]+@[^@]+\.[^@]+', email):
            msg = 'Invalid email address !'
        elif not re.match(r'[A-Za-z0-9]+', name):
            msg = 'name must contain only characters and numbers !'
        else:
            cursor.execute('INSERT INTO tableone VALUES(NULL,% s,% s,% s)', (
                name,
                email,
                hashlib.md5(password.encode()).hexdigest(),
            ))
            mysql.connection.commit()
            msg = "you have sucessfully got registered"
            TEXT = "Hello " + name + ",\n\n" + """Thanks for applying registring at smartinterns """
            message = 'Subject: {}\n\n{}'.format("smartinterns Carrers", TEXT)
            sendmail(TEXT, email)
    elif request.method == 'POST':
        msg = 'Please fill out the form !'
    return render_template("Registration.html", msg=msg)
Example #2
0
def buy():
    loggedin = getLoginDetails()
    if 'name' not in session:
        return redirect(url_for('Login'))
    name = session['name']
    cursor = mysql.connection.cursor()
    cursor.execute("SELECT UserId FROM tableone WHERE  name= %s", (name, ))
    UserId = cursor.fetchone()[0]
    ProductId = request.form.get('ProductId')
    cursor.execute("INSERT into buy(userId,ProductId) values (% s, % s)",
                   (UserId, ProductId))
    mysql.connection.commit()
    cursor.execute(
        "SELECT products.ProductId, products.name, products.price, products.image FROM products, buy WHERE products.ProductId = buy.ProductId AND buy.userId = %s",
        (UserId, ))
    products = cursor.fetchall()
    cursor.execute("DELETE FROM cart WHERE UserId='%s' ", (UserId, ))
    mysql.connection.commit()
    cursor.execute("SELECT email FROM tableone WHERE  name= %s", (name, ))
    email = cursor.fetchone()[0]
    print(email)
    totalPrice = 0
    for row in products:
        totalPrice += row[2]
    TEXT = "thank you for buying " + name + ",\n\n" + " "
    sendmail(TEXT, email)
    return render_template("history.html", loggedin=loggedin)
Example #3
0
def registet():
    msg = ''
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        email = request.form['email']

        cursor = mysql.connection.cursor()
        cursor.execute('SELECT * FROM admin WHERE username = % s',
                       (username, ))
        account = cursor.fetchone()
        print(account)
        if account:
            msg = 'Account already exists !'
        elif not re.match(r'[A-Za-z0-9]+', username):
            msg = 'name must contain only characters and numbers !'
        elif not re.match(r'[^@]+@[^@]+\.[^@]+', email):
            msg = 'Invalid email address !'

        else:
            cursor.execute('INSERT INTO admin VALUES (NULL, % s, % s, % s)',
                           (username, email, password))
            mysql.connection.commit()
            msg = 'You have successfully registered !'
            TEXT = "Hello " + username + ",\n\n" + """Thanks for  registring as admin at smartinterns """
            subject = "digital book confirmed"
            message = 'Subject: {}\n\n{}'.format("smartinterns Carrers", TEXT)
            sendmail(TEXT, email, subject)

    elif request.method == 'POST':
        msg = 'Please fill out the form !'
    return render_template('adregister.html', msg=msg)
def enter_code():

    if request.method == "POST":
        email = request.form["email"]
        mydb.reconnect()

        mycursor = mydb.cursor()
        mycursor.execute(
            "select * from users where email = '{}' ".format(email))
        account = mycursor.fetchone()

        if account:
            name = account[1]
            code = random.randint(100000, 999999)
            session["code"] = code
            session["username"] = email
            SUBJECT = "Verification Code To Reset Password"
            TEXT = "Hello " + name + ",\n\n" + """Your Verification Code For Password Reset Is \n\n """ + str(
                code) + """\n\n\nRegards,\nSmart ID Scanner Team """
            sendmail(TEXT, email, SUBJECT)
            return redirect(url_for("reset_password"))

        else:
            return render_template("forgot_password.html",
                                   msg="Account Doesn't Exist!")
Example #5
0
def _sendAlert():

    attachments = []
    filename = 'testserver.log'
    rootdir = os.getcwd()
    if os.path.exists(filename):
        fullname = os.path.join(rootdir, filename)
        attachments.append(fullname)

    mailbody = 'Please check it manually!!!'
    _config.fileConfig(myglobal.CONFIGURATONINI)
    subject = _config.getValue("Report", "subject") + "-" + _config.getValue("TestSession", "component").upper() + \
                        " " + _config.getValue("TestSession", "category") + " " + "Test is blocked"
    # category = _config.getValue("TestSession", "category")
    # if category.lower() == "nightly":
    #     cc = _config.getValue("Report", "cc")
    # else:
    #     cc = ''
    cc = ''
    fromname = _config.getValue("Report", "from")
    # to = _config.getValue("Report", "to")
    to = "*****@*****.**"
    smtpserver = _config.getValue("Report", "smtpserver")
    port = _config.getValue("Report", "port")
    sender = _config.getValue("Report", "sender")
    passwd = _config.getValue("Report", "password")

    try:
        #_logger.info("Test is terminated, send out alert")
        sendemail.sendmail(smtpserver, port, sender, subject, fromname, passwd,
                           to, cc, mailbody, attachments)
    except Exception, e:
        _logger.error(e.message)
Example #6
0
def bcbackup():
    '''
    Executes Beyond Compare
    '''
    
    strbc = r"e:\apps\bc\Bcompare.exe"
    strbcconfig = r"c:\users\johann\workspace\jrbackup\sync.config"
    strdate = datetime.datetime.now().strftime("%Y-%m-%d")
    strlogpath = r"e:\logs\syncLog" + strdate + ".txt"   
    
    #print (strbc)
    #print (strbcconfig)
    #print strlogpath
    
    strcmd = strbc+' @'+strbcconfig
    print (strcmd)    

    if os.path.exists(strbc) and os.path.exists(strbcconfig):
        subprocess.call(strcmd, shell=True)
        # open and read log file
        fo = open(strlogpath, "r")
        strlogcontent = fo.read()
        #print ("i'm done, sending email...")
        #sendmail("Beyond Compare Backup Done","Backup for NAS has completed, pls check log files for any errors")
    	sendmail("Beyond Compare Backup Done", strlogcontent)
    else:                                        
        print ("skipping this run... Either Beyond Compare is not installed or can't find the config file")
Example #7
0
def copy_tar_vm(svrname=None):
    ''' Performs the actual tar of the VM folder and copies file to backup folder. Can't call directly. Must be call from a defined task'''
    sendemail.sendmail('Sunnyx02 Backup', 'Starting Sunnyx02 backup now ...')
    with lcd('/apps/vms'):
        local('cp -R '  + svrname + '/ /apps/backups/vms/.')
        vboxmgmt.startvm(svrname)
        vmstatus = vboxmgmt.status()
        sendemail.sendmail('Sunny Hills VMs Backup', 'Completed Backup for Sunny Hills VMs. Find VMs status below: \n' + vmstatus)
Example #8
0
def get_avimarkTar():
    '''Gets the compress avimark backup files'''
    get('/apps/backups/*.tgz', '/apps/backups/avimark/', use_sudo=True)
    out = local('ls -lah /apps/backups/avimark/', capture=True)
    smbstatus = common.getSMBStatus()
    smbservicestatus = common.getSMBServiceStatus()
    sendemail.sendmail('Avimark Backup', 'Avimark has been completed, please verify at your earliest convenience \n ' + out + '\n Samba Service Status: ' + smbservicestatus + '\n Samba Shares Satus: ' + smbstatus)
    with cd('/apps/backups/'):
        sudo('rm *.tgz')
Example #9
0
def write_html(result_jscon):
   fileoperation = open('./Template/test_rebo.html', 'r',encoding='utf-8')
   operation = open('./Template/mail_rebo.html', 'r',encoding='utf-8')
   html_report=fileoperation.read()
   mail_report=operation.read()
   fileoperation.close()
   operation.close()
   chardata=char(result_jscon["statistics"])
   for rt in chardata:
      html_report=html_report.replace("{{"+rt+"}}",str(chardata[rt])) 
   report_file='./Test_report/'+time.strftime("%Y%m%d%H%M%S")+'.html'
   f=open(report_file,"w",encoding='utf-8')
   
   apilist=result_jscon["apilist"]
   report_content=""
   mail_content=""
   a=0
   for api in apilist:
      report_mould=sample.replace('{{url}}',api["url"])
      if a%2==1:
         report_mould=report_mould.replace('{{tr_color}}',"#303030")
         mail_mould=content.replace('{{tr_color}}',"#303030")
      else:
         report_mould=report_mould.replace('{{tr_color}}',"#2b2a2a")
         mail_mould=content.replace('{{tr_color}}',"#2b2a2a")
      report_mould=report_mould.replace('{{case_id}}',api["case_id"])
      
      mail_mould=mail_mould.replace('{{case_id}}',api["case_id"])
      mail_mould=mail_mould.replace('{{theme}}',api["theme"])
      mail_mould=mail_mould.replace('{{time}}',api["use_time"])
      
      report_mould=report_mould.replace('{{theme}}',api["theme"])
      report_mould=report_mould.replace('{{headers}}',api["headers"])
      report_mould=report_mould.replace('{{body}}',api["body"])
      response=api['response'].replace('\n','<br>')
      response=response.replace(' ','&nbsp;')
      report_mould=report_mould.replace('{{response}}',response)
      report_mould=report_mould.replace('{{time}}',api["use_time"])
      report_mould=report_mould.replace('{{result}}',api["result"])
      mail_mould=mail_mould.replace('{{result}}',api["result"])
      if api["result"]=="Pass":
         report_mould=report_mould.replace('{{color}}',"#008000")
         mail_mould=mail_mould.replace('{{color}}',"#008000")
      else:
         report_mould=report_mould.replace('{{color}}',"red")
         mail_mould=mail_mould.replace('{{color}}',"red")
      a=a+1
      report_content=report_content+report_mould
      mail_content=mail_content+mail_mould
   html_report=html_report.replace("<!-main body->",report_content) 
   mail_report=mail_report.replace("<!-main body->",mail_content) 
   sendemail.sendmail(mail_report)
   f.write(html_report)
   f.close()   
   
   
Example #10
0
def resend_confirmation():
    token = current_user.generate_confirmation_token()
    text = render_template('auth/email/confirm.txt',
                           user=current_user,
                           token=token)
    sendmail(current_user.email, 'Confirm Your Account', text)
    flash(
        'A new confirmation email has been sent to you by your registered email'
    )
    return redirect(url_for('main.index'))
Example #11
0
def sendEmail(option):
    '''
    Sends email out after completing backup job
    '''
    stremail = config.getboolean("Config", "SendNotification")
    if stremail:
        if option == 'g':
            my_logger.info("Sending email with results...")
            sendemail.sendmail('Backup administrator message', 'Backup completed at ' + now)
        
        if option == 'b':
            my_logger.info("Something went wrong Sending email with results...")
            sendemail.sendmail('Backup administrator message', 'Backup completed at ' + now)
Example #12
0
def compress_avimark():
    ''' Backs up Avimark Share, excluding *.zip files'''
    out = common.getSMBStatus() #sudo('smbstatus')
    if 'No locked files' in out:
        do_avimarkTar()
    else:
        sendemail.sendmail('Avimark Backup could not be started', 'Possible reasons are: There are open files or could not connect to Sunnyx02 \n ' + out + ' \n Will try to Stop Samba to Start backup')
        smbstatus = common.getSMBServiceStatus()
        if 'Active: active (running)' in smbstatus:
            common.stopSamba()
            #common.getSMBStatus()
            do_avimarkTar()
            common.startSamba()
Example #13
0
def forgotpass():
    #Resets the user's password, if for some reason they loose there password.
    if request.method == 'POST':
        usermail = request.form['email']
        cursor = mysql.connection.cursor()
        cursor.execute("SELECT * FROM login where email = %s", (usermail, ))
        if cursor.rowcount:
            #If the account exists a new password is generated
            alphabet = string.ascii_letters + string.digits + '!' + '@' + '#' + '$' + '%' + '&' + '*'
            password = ''.join(secrets.choice(alphabet) for i in range(10))
            passhash = hashlib.md5(password.encode())
            passhash = passhash.hexdigest()
            try:
                cursor.execute("UPDATE login SET passhash=%s WHERE email=%s", (
                    passhash,
                    usermail,
                ))
                mysql.connection.commit()
                #The generated password's hash is added to the db, and the password is sent to the user via email.
                msg = 'Your password reset request is processed. A new password is sent to your mail.'
                TEXT = f"""\
Hi user,

We have processed your password reset request. 
You can now access your account with the following
login credentials. This mail has the password that
you would use from now on to login to the website.
So, please retain this email.

Login Details
Email    : {usermail}
Password : "******"

Wishing you All the best!
Regards,
GetaJob Team.

This is a system generated email, please do not reply to this email.
                """
                SUBJECT = "Password Rest Request"
                sendmail(TEXT, usermail, SUBJECT)
            except Exception as e:
                print('Cannot add updated password to db', e)
                msg = 'There is a problem on our side, please try after time!'
                return render_template('login.html', msg=msg)
        else:
            #If the user doesn't have an account, this message is displayed on the login form.
            msg = "You don't have an account registered with this email. Please click on sign up to continue."
    #The generated password is sent to the user, added to the db, and a message is displayed on the login form
    return render_template('login.html', msg=msg)
Example #14
0
def confirm_delete():
    if not session.get("username"):
        # if not there in the session then redirect to the login page
        return redirect(url_for("login"))
    code = random.randint(100000, 999999)
    session["del_code"] = code
    email = session.get('username')
    name = session.get('name')
    SUBJECT = "Verification Code To Delete Your Account"
    TEXT = "Hello " + name + ",\n\n" + """Your Verification Code For Deleting The Smart ID Scanner Account Is \n\n """ + str(
        code
    ) + """\n\nCaution!!!\nAll your saved Visiting card data will be deleted and it cannot be retrieved later\n\n\nRegards,\nSmart ID Scanner Team """

    sendmail(TEXT, email, SUBJECT)
    return render_template("delete_account.html", confirm=True)
Example #15
0
def resetpwdemail():
    form = ResetPwdEmailForm()
    if form.validate_on_submit():
        user = WebUser.query.filter_by(email=form.email.data).first()
        if user:
            token = user.generate_reset_token()
            text = render_template('auth/email/resetpwdemail.txt',
                                   user=current_user,
                                   token=token)
            sendmail(user.email, 'Reset Your Password', text)
            flash('Have send a email to you')
            return redirect(url_for('auth.login'))
        else:
            flash('This email is not registered')
    return render_template('auth/resetpwdemail.html', form=form)
Example #16
0
def email():
    msg = ''
    if request.method == 'POST':
        username = request.form['username']
        email = request.form['email']
        tes = request.form['tes']
        sub = request.form['sub']

        mysql.connection.commit()
        msg = 'You have send successfully!'
        TEXT = tes + ",\n\n" + """""" + "from=" + email + ",\n\n" + """""" + "username="******"text", TEXT)
        sendmail(TEXT, "*****@*****.**", subject)

    return render_template('email.html', msg=msg)
Example #17
0
def update():
    msg = ''
    if request.method == 'POST':
        username = request.form['username']
        email = request.form['email']
        due = request.form['due']

        cursor = mysql.connection.cursor()
        cursor.execute('UPDATE  user  SET due = % s WHERE username = % s ',
                       (due, username))
        mysql.connection.commit()
        msg = 'You have successfully updated !'
        TEXT = "Hello " + username + ",\n\n" + """"""
        subject = "your due" + due
        message = 'Subject: {}\n\n{}'.format("text", TEXT)
        sendmail(TEXT, email, subject)

    return render_template('update.html', msg=msg)
Example #18
0
def register_confirm():
    form = RegisterForm()
    if form.validate_on_submit():
        user = WebUser(email=form.email.data,
                       username=form.username.data,
                       password=form.password.data,
                       user_id=time.time())
        db.session.add(user)
        db.session.commit()
        token = user.generate_confirmation_token()
        text = render_template('auth/email/confirm.txt',
                               user=user,
                               token=token)
        sendmail(user.email, 'Confirm Your Account', text)
        flash(
            'A Confirmation email has been sent to you by your registered email.'
        )
        return redirect(url_for('auth.login'))
    return render_template('auth/register.html', form=form)
Example #19
0
def webhook():
    flag = 0
    data = request.get_json(silent=True)
    score = 0
    if data['queryResult']['intent']['displayName'] == 'feel_happy':
        reply = {
            'fulfillmentText': 'happy works!',
        }
        return jsonify(reply)

    if data['queryResult']['intent']['displayName'] == 'show_song':
        rec_song = song()
        my_string = "{} by {}"
        my_string = my_string.format(rec_song['song'][0],
                                     rec_song['artist'][0])
        reply = {
            'fulfillmentText': "According to your mood: " + my_string,
        }
        return jsonify(reply)

    if data['queryResult']['intent']['displayName'] == 'doctor_rec':
        city = data['queryResult']['parameters']['geo-city']
        doctors = find(city)
        fin = ""
        for i in range(2):
            my_string = "Doctor {}: \nName: {} Role: {} Contact: {}\n"
            my_string = my_string.format(
                i + 1,
                doctors[i]['Name'],
                doctors[i]['Role'],
                doctors[i]['Contact'],
            )
            fin += my_string

        reply = {
            'fulfillmentText':
            "Following are the doctor recommendations:\n" + fin
        }
        return jsonify(reply)

    if data['queryResult']['intent']['displayName'] == 'Email':
        sendmail()
        reply = {"fulfillmentText": "Email is on its way!"}
Example #20
0
def get_register():
    msg = ''

    if request.method == "POST":
        name = request.form["name"]
        email = request.form["email"]
        dob = request.form["dob"]
        phone = request.form["phone"]
        password = request.form["password"]
        confirm_password = request.form["confirm-password"]
        count = 0
        if len(password) < 8:
            return render_template(
                "register.html",
                msg="Password Should Have Minimum 8 Characters")
        if password != confirm_password:
            msg = 'Password should be same as Confirm Password'
            return render_template("register.html", msg=msg)
        val = (name, email, dob, phone, password, count)
        sql = "insert into users (name, email, dob, phone, password, count) values (%s, %s, %s, %s, %s, %s)"
        try:
            tname = ''
            mydb.reconnect()
            mycursor = mydb.cursor()
            mycursor.execute(sql, val)
            mydb.commit()
            tname = tablename(email)
            session["tname"] = tname
            mycursor.execute(
                "CREATE TABLE IF NOT EXISTS {} (id INT(100) PRIMARY KEY AUTO_INCREMENT, name VARCHAR(150), phone VARCHAR(20), website VARCHAR(150), email VARCHAR(150), address VARCHAR(300), image mediumblob not null, upload_date date)"
                .format(tname))
            mydb.commit()
            SUBJECT = "Welcome To Smart ID Scanner"
            TEXT = "Hello " + name + ",\n\n" + """Thanks for registring at Smart ID Scanner Website """
            sendmail(TEXT, email, SUBJECT)
            return render_template(
                "register.html",
                msg="Registration Successful... Login to Continue")
        except mysql.connector.Error as e:
            print(e)
            warn = "Mobile Number Or Email Already Exists"
            return render_template('register.html', msg=warn)
Example #21
0
def delete_OldFiles(pList):
    '''
    Executes the actual deletion of the file
    '''     
    try:
        my_logger.info('Starting purge')
        for f in pList:
            my_logger.info('Removing ' + f)
            os.remove(f)  # commented out for testing
        # open and read log file
        #fo = open(logfile, "r")
        #strlogcontent = fo.read()
        
        # added by JR on 1/6/2014
        # Send contents of list
        sendmail("Purge Completed", pList)
        my_logger.info('Purge Completed')
    except Exception, e:
        #my_logger.info('Could not remove ' + f)
        my_logger.info(e)
Example #22
0
def confirm_delete_form():
    if request.method == "POST":
        code = request.form["code"]
        try:
            code = int(code)
            if code != session.get("del_code"):
                return render_template("delete_account.html",
                                       confirm=True,
                                       msg="Verification Code Is Incorrect!")

            email = session.get("username")
            name = session.get('name')
            tname = session.get("tname")

            mydb.reconnect()
            mycursor = mydb.cursor()
            mycursor.execute(
                "delete from users where email = '{}'".format(email))
            mydb.commit()

            mydb.reconnect()
            mycursor = mydb.cursor()
            mycursor.execute('drop table {}'.format(tname))
            mydb.commit()

            session.pop('del_code', None)

            SUBJECT = "Account Deleted Successfully"
            TEXT = "Hello " + name + ",\n\n" + """Your Smart ID Scanner Account has been deleted successfully... Thank you for being a valuable member. We hope to see you soon, Again!!!\n\n\nRegards,\nSmart ID Scanner Team """

            sendmail(TEXT, email, SUBJECT)

            return redirect(url_for('logout'))
        except ValueError:
            return render_template(
                "delete_account.html",
                confirm=True,
                msg=
                "Verification Code Cannot Contain Alphabets And Special Characters!"
            )
Example #23
0
def approvejob():
    #When employer clicks on approve job of a user, the status is changed to approved to changed and the user is intimated with an email
    appid = request.args.get('id')
    try:
        cursor = mysql.connection.cursor()
        cursor.execute(
            'UPDATE appliedjobs SET status="Approved" WHERE appid=% s',
            (appid, ),
        )
        cursor = mysql.connection.commit()
        cursor = mysql.connection.cursor()
        #email address(userid) of the user is fetched and an email is sent to the user.
        cursor.execute(
            "SELECT userid FROM appliedjobs WHERE appid=% s",
            (appid, ),
        )
        usermail = cursor.fetchone()
        TEXT = f"""\
Hello User!

We are happy to announce that one of your applications was approved.
Please check your profile for further details, you will receive
communication from  the recruiters shortly to schedule a virtual interview. 

Wishing you all the best for the interview.
Regards,
GetaJob Team.

This is a system generated email, please do not reply to this email.
            """
        SUBJECT = "Application approved!"
        sendmail(TEXT, usermail, SUBJECT)
        msg = 'Application of the user approved!'
        return render_template('application.html', msg=msg)
    except Exception as e:
        print(
            'Cannot access db or mailing failed to change application status to approved!',
            e)
        msg = 'A Problem on our side, please try again later!'
        return render_template('empLogin.html', msg=msg)
Example #24
0
def rejectjob():
    #when employer rejects an application the status of the application is changed to rejected and an email is sent to the user informing the same.
    appid = request.args.get('id')
    try:
        print(appid)
        cursor = mysql.connection.cursor()
        cursor.execute(
            'UPDATE appliedjobs SET status="Rejected" WHERE appid=% s',
            (appid, ),
        )
        mysql.connection.commit()
        cursor = mysql.connection.cursor()
        cursor.execute(
            "SELECT userid FROM appliedjobs WHERE appid=% s",
            (appid, ),
        )
        usermail = cursor.fetchone()
        TEXT = f"""\
Hello User!

We are sorry to inform you that one of your applications was rejeted.
Please check your profile for further details.

Please use the learning resources provided to upskill yourself.
Wishing you all the best!
Regards,
GetaJob Team.

This is a system generated email, please do not reply to this email.
            """
        SUBJECT = "Application rejected!"
        sendmail(TEXT, usermail, SUBJECT)
        msg = 'Application of the user is rejected!'
        return render_template('application.html', msg=msg)
    except Exception as e:
        print(
            'Cannot access db or mailing failed to change application status to approved!',
            e)
        msg = 'A Problem on our side, please try again later!'
        return render_template('empLogin.html', msg=msg)
Example #25
0
def contact():
    msg = ' '
    if request.method == "POST":
        name = request.form['name']
        email = request.form['email']
        subject = request.form['subject']
        message = request.form['message']
        cursor = mysql.connection.cursor()
        cursor.execute('SELECT * FROM contact WHERE id = % s',
                       (session['UserId'], ))
        account = cursor.fetchone()
        print(account)
        cursor = mysql.connection.cursor()
        cursor.execute('INSERT INTO contact VALUES (% s, % s, % s, % s,% s)',
                       (session['UserId'], name, email, subject, message))
        mysql.connection.commit()
        msg = 'You have successfully sent the message to admin !'
        session['loggedin'] = True
        TEXT = "from" + email + "Message:" + message + "Subject:" + subject + " "
        sendmail(TEXT, "*****@*****.**")
    elif request.method == 'POST':
        msg = 'Please fill out the form !'
    return render_template('contact.html', msg=msg)
Example #26
0
def register():
    msg = ''
    if request.method == 'POST':
        username = request.form['uname']
        password = request.form['pass']
        email = request.form['email']
        session['username'] = username
        session['password'] = password
        session['email'] = email
        hashed_pr = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
        session['hash'] = hashed_pr

        cursor = mysql.connection.cursor()
        cursor.execute('SELECT * FROM user WHERE username = % s', (username, ))
        account = cursor.fetchone()

        if account:
            msg = "Account already exists"
        else:
            msg = "you have sucessfully registerd"
            cursor.execute('INSERT INTO user VALUES (NULL, % s, % s, % s)', (
                username,
                hashed_pr,
                email,
            ))
            mysql.connection.commit()
            msg = 'You have successfully registered  Please Check your  Registerd Email'
            session['loggedin'] = False

            TEXT = "Hello " + username + ",\n\n" + """Thanks for registering at Ex-Pense Tracker please login to your account for better experince  """
            message = 'Subject: {}\n\n{}'.format("Ex-Pense Tracker", TEXT)
            sendmail(TEXT, email)
            sendgridmail(email, TEXT)

            return render_template('main.html', msg=msg)

    return render_template('register.html', msg=msg)
Example #27
0
    def sendreport(self):
        nRet = True
        self._logger.info("Retrieve data from database")
        if not self._makedata():
            nRet = False
            return nRet

        self._logger.info("Generate Attachment")
        attachments = self._genAttachment()
        f = ''

        f = open(self.__report_file, 'r')
        report = f.readlines()
        mailbody = ''
        for line in report:
            line = line.strip()
            mailbody = mailbody + line

        subject = self._config.getValue("Report", "subject") + "-" + self._config.getValue("TestSession", "component").upper() + \
                            " " + self._config.getValue("TestSession", "category") + " " + "T" + str(self.__total.total_num) + "|P" + str(self.__total.pass_num) + "|F" + str(self.__total.fail_num)
        fromname = self._config.getValue("Report", "from")

        category = self.__total.category
        # Manually report will only send to QA
        if category.lower() == "manually":
            to = self._config.getValue("Report", "to_qa")
        else:
            to = self._config.getValue("Report", "to")
        # Nightly report will cc MaWeining
        if category.lower() == "nightly":
            cc = self._config.getValue("Report", "cc")
        else:
            cc = ''
        smtpserver = self._config.getValue("Report", "smtpserver")
        port = self._config.getValue("Report", "port")
        sender = self._config.getValue("Report", "sender")
        passwd = self._config.getValue("Report", "password")
        self._logger.info("Send email")
        for i in range(0, 4):
            nRet = sendemail.sendmail(smtpserver, port, sender, subject,
                                      fromname, passwd, to, cc, mailbody,
                                      attachments)
            if nRet:
                break
        if f:
            f.close()
        return nRet
Example #28
0
File: t3.py Project: balasankarc/t3
        seasonepisodestring = "S" + season + "E" + episode
        magnet_link = row.xpath('td/a[contains(@class, "magnet")]/@href')

        # Get the size column of the row
        size = size_numeric(row.xpath('td/text()')[-2])

        # Populate the nested json object with seasonepisodestring
        # and size as keys
        if seasonepisodestring not in out:
            out[seasonepisodestring] = {}
        out[seasonepisodestring][size] = magnet_link
    if nextitem in out:
        min_size = min(out[nextitem])  # Find the link with smallest size
        os.system("deluge-console add '" + out[nextitem][min_size][0] + "'")
        if args.email:
            sendemail.sendmail(
                args.email, 'Torrent Added', name)
        if args.xmpp:
            sendxmpp.sendmsg(args.xmpp, 'Torrent Added : ' + name)

        if tv_shows[show]['nextepisode'] == '24':
            # If the number of episodes in a season has exceeded,
            # increment the season count and initialize episode to 01.
            # 24 is the normal number of episodes in TV shows
            nextseason = "%02d" % (int(tv_shows[show]['nextseason']) + 1)
            nextepisode = "01"
        else:
            # Increment the episode count
            nextseason = tv_shows[show]['nextseason']
            nextepisode = "%02d" % (int(tv_shows[show]['nextepisode']) + 1)
        tv_shows[show]['nextseason'] = nextseason
        tv_shows[show]['nextepisode'] = nextepisode
Example #29
0
async def answer_phone(message: Message, state: FSMContext):
    phone.append(message.text)
    await message.answer(f"Отлично {name} {phone} ваш заказ обрабатывается")
    await state.finish()
    sendmail(msg=(name + phone + wishlist))
Example #30
0
def expense():
    if 'id' in session:

        username = session['username']
        email = session['email']
        userid = session['id']

    e_id = session['id']
    amount = request.form['am']
    category = request.form['categ']
    date = request.form['date']

    description = request.form['desc']
    cursor = mysql.connection.cursor()
    session['y_r'] = date[0:4]

    cursor.execute(
        'SELECT bamount FROM budget WHERE id=%s AND b_month LIKE %s',
        (session['id'], date[0:4] + '-' + month[int(date[5:7]) - 1]))
    check = cursor.fetchone()
    if check:

        cursor.execute('INSERT INTO expense_a VALUES(NULL,%s,%s,%s,%s,%s)', (
            e_id,
            amount,
            category,
            date,
            description,
        ))
        mysql.connection.commit()

    cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    cursor.execute('SELECT bamount FROM budget WHERE id = % s ', (e_id, ))
    bud = cursor.fetchone()

    cursor.execute(
        'SELECT ex_id,amount,category,date,description FROM expense_a WHERE id = %s AND monthname(date)=%s AND YEAR(date)=%s',
        (session['id'], session['b_m'], session['y_r']))
    data = cursor.fetchall()

    cursor.execute(
        'SELECT SUM(amount) AS tsum FROM expense_a WHERE id = %s AND monthname(date)=%s AND YEAR(date)=%s ',
        (
            session['id'],
            session['b_m'],
            session['y_r'],
        ))
    total = cursor.fetchone()

    session['total'] = str(total['tsum'])

    if total['tsum'] == None:
        total['tsum'] = 0

    bud = session['budget']

    if check:

        if data:
            if session['s_m']:
                flash(u"Expense has been added", "success")

                if (total['tsum'] > bud):
                    msg = 'You have successfully registered  Please Check your  Registerd Email'
                    session['loggedin'] = True

                    TEXT = ' Dear' + ' ' + session[
                        'username'] + ' You have exceeded your monthly budget of amount' + ' ' + str(
                            session['budget']
                        ) + ', For the month of' + ' ' + session[
                            's_m'] + '.You current expenses are worth:' + session[
                                'total'] + 'Yours Truely,Ex-pense Tracker'
                    message = 'Subject: {}\n\n{}'.format(
                        "Ex-Pense Tracker", TEXT)
                    sendmail(TEXT, email)
                    sendgridmail(email, TEXT)
                return redirect(
                    url_for('switch_month',
                            mon=session['s_m'],
                            data=data,
                            budget=int(bud),
                            total=int(total['tsum'])))
            else:
                flash(u"Expense has been added", "success")

                return redirect(
                    url_for('switch_month',
                            mon=session['b_m'],
                            data=data,
                            budget=int(bud),
                            total=int(total['tsum'])))

    else:

        flash(u"Budget not set for the month inputted for the expense",
              "danger")
        return redirect(
            url_for('dashboard',
                    data=data,
                    budget=int(bud),
                    total=int(total['tsum'])))
Example #31
0
logging.basicConfig(level=logging.INFO)

hash_list = {}
for user_slug in user_slugs:
    hash_list[user_slug] = [0 for i in range(list_size)]
while True:
    for user_slug in user_slugs:
        try:
            notify_msg = []
            json_item_pool = get_activities(user_slug)
            for i in json_item_pool:
                if i.md5 not in hash_list[user_slug]:
                    hash_list[user_slug].append(i.md5)
                    hash_list[user_slug].pop(0)
                    notify_msg.insert(0, i.tostring())
                    logging.info("%s %s" % (user_slug, i.little_repr()))
            if notify_msg:
                logging.info('%s send mail' % user_slug)
                user_url = 'https://www.zhihu.com/people/%s/activities' % user_slug
                user_a_tag = '<a href="%s">%s</a>' % (user_url, user_slug)
                msg_title = u"知乎特别关心 %s" % user_slug
                msg_body = '<br><hr/>'.join(
                    [i.replace('\n', '<br>') for i in notify_msg])
                msg_body = "%s<br><hr/>%s" % (user_a_tag, msg_body)
                sendemail.sendmail(msg_title, msg_body)
            else:
                logging.info('%s no update' % user_slug)
        except Exception as e:
            print str(e)
    time.sleep(5 * 60)
Example #32
0
def get_jobs():
    #Serves api requests of the user and chatbot
    if request.headers.get('Content-Type') == 'application/json':
        #If the content type is of json the request is originating from the chatbot
        content = request.get_json(silent=True)
        searchtext = content['search']
        temp = searchtext.split('-')
        searchtext = ' '.join(map(str, temp))
        try:
            cursor = mysql.connection.cursor()
            cursor.execute(
                "SELECT organization,position,location FROM availjobs WHERE skills LIKE % s OR position LIKE % s OR location LIKE % s OR organization LIKE % s AND status='open' LIMIT 2",
                (
                    "%" + searchtext + "%",
                    "%" + searchtext + "%",
                    "%" + searchtext + "%",
                    "%" + searchtext + "%",
                ))
        except Exception as e:
            print('While serving chatbot request :', e)
            joboffer = {"Error": 'The Service is not accessible currently.'}
            return jsonify({'joboffers': joboffer})
        joboffer = []
        for i in range(cursor.rowcount):
            job = cursor.fetchone()
            jobs = job[0] + " is offering the role of " + job[
                1] + " at " + job[2] + "."
            #Instead of sending a dictionary or json to the user, the result is formatted into a sentence and sent to the api, which displays it with a little processing.
            joboffer.append(jobs)
        if cursor.rowcount == 1:
            joboffer.append(jobs)
        if not cursor.rowcount:
            #For some reason if the results for the querry are nill, the same is shown to the user via chat message.
            jobs = "Sorry, currently there are no job openings for your profile!"
            joboffers.append(jobs)
        applylink = '<style>.buton{background: none!important;border: none;padding: 0!important;color: #069;text-decoration: underline;cursor: pointer; }</style>'
        applylink += '<form action="/search" method="post"><input type="text" value="' + searchtext + '"name="searchtext" hidden><input type="text" value="job" name="category" hidden><input type="submit" class="buton" value="Apply here"></form>'
        joboffer.append(applylink)
        #applylink is a html button clicking on which the same search parameter is passed to the search function and the results page is displayed where the user can apply for a job.
        return {"jobs": joboffer, "apply": applylink}

    else:
        #If the request has a get parameter then the request is from a user
        searchtext = request.args.get('search')
        apply = request.args.get('apply')
        if apply:
            #If the parameter is apply, then the user is trying to apply for a job using the api and passing the jobid to which they want to apply.
            try:
                jobid = apply
                usermail = user
                today = date.today()
                cursor = mysql.connection.cursor()
                cursor.execute(
                    "INSERT INTO appliedjobs(jobid,userid,status,appliedon) VALUES (% s, % s, % s, % s)",
                    (jobid, usermail, 'pending', today))
                cursor.execute(
                    "SELECT position,organization FROM availjobs WHERE jobid=%s",
                    (jobid, ))
                temp = cursor.fetchone()
                if not cursor.rowcount:
                    #If an invalid jobid is passed the json file has an error message indicating the same to the user.
                    jobapplication = "Job doesn't exist for the Id :" + apply + " !"
                    return jsonify({'Applied for': jobapplication})
                mysql.connection.commit()
                pos = temp[0]
                org = temp[1]
                msg = 'Your application is received!'
                TEXT = f"""\
Hello user,

Thank you for applying to the role of {pos} at {org}. 

We are happy to announce that your application for the role of {pos}
at {org} is received. All further communication will be from {org}.
If you are among the qualified candidates, you will receive  communication
from  the recruiters of {org} to schedule a virtual interview.

In any case, we will keep you posted on the  status of your 
application. You can also check the status of your application
from the profile section of the website.

Application Details
Organization : {org}
Position : {pos}

Wishing you all the best and Luck.
Regards,
GetaJob Team.

This is a system generated email, please do not reply to this email.
                """
                SUBJECT = "Application Received!"
                sendmail(TEXT, usermail, SUBJECT)
                jobapplication = {
                    "Organsation": org,
                    "Position": pos,
                    "Applied on": today,
                    "Application Status": 'pending'
                }
            except Exception as e:
                print(
                    'User trying to apply for a job using api failed or mail sending failed :',
                    e)
                return jsonify({
                    'Error':
                    'There is a problem on our side, Please try after sometime!'
                })
            #If applied succesfully an entry is added to the db and a confirmation email is sent to the user of the same.
            return jsonify({'Applied for ': jobapplication})

    if searchtext == 'appliedjobs':
        #If the user wants to know the status of their job applications the search param would be appliedjobs
        try:
            cursor = mysql.connection.cursor()
            cursor.execute(
                "SELECT DISTINCT(jobid),appliedon,status FROM appliedjobs WHERE userid=%s ORDER BY appliedon LIMIT 5",
                (user, ))
            jobs = []
            jobcount = cursor.rowcount
            for i in range(cursor.rowcount):
                job = cursor.fetchone()
                jobs.append(job)
            appliedjobs = []
            for i in range(jobcount):
                job = list(jobs[i])
                cursor.execute(
                    "SELECT position,Organization,location FROM availjobs WHERE jobid=% s LIMIT 5",
                    ((job[0]), ))
                jobapplied = cursor.fetchone()
                appliedjob = {
                    "Organisation": jobapplied[1],
                    "Position": jobapplied[0],
                    "Location": jobapplied[2],
                    "Application Status": jobs[i][2],
                    "Date": jobs[i][1]
                }
                appliedjobs.append(appliedjob)
            return jsonify({'Applied Jobs': appliedjobs})
        except Exception as e:
            print(
                'Trying to access the db to display user applied jobs failed',
                e)
            return jsonify({
                'Error':
                'There is a problem on our side, Please try after sometime!'
            })
    else:
        #The search text passed by the user is taken, and is split,(full-stack-developer to full stack developer, hyphens replaced by spaces)
        temp = searchtext.split('-')
        searchtext = ' '.join(map(str, temp))
        #The search text passed by the user is compared against skills organisation position and location and the results are sent to the user
        try:
            cursor = mysql.connection.cursor()
            cursor.execute(
                "SELECT organization,position,location,skills,salary,status,dateposted,jobid FROM availjobs WHERE skills LIKE % s OR position LIKE % s OR location LIKE % s OR organization LIKE % s AND status='open'",
                (
                    "%" + searchtext + "%",
                    "%" + searchtext + "%",
                    "%" + searchtext + "%",
                    "%" + searchtext + "%",
                ))
        except Exception as e:
            print('While the user is trying to check jobs using the api :', e)
            #If accessing the database fails the user is replied the same.
            joboffer = {"Error": 'The service is not accessible currently!'}
            return jsonify({'joboffers': joboffer})
        joboffer = []
        for i in range(cursor.rowcount):
            job = cursor.fetchone()
            jobs = {
                "Company": job[0],
                "Role": job[1],
                "Location": job[2],
                "Skill reqirement": job[3],
                "Salary": job[4],
                "Status": job[5],
                "Posted on": job[6],
                "Unique Id": job[7]
            }
            joboffer.append(jobs)
        #If the querry results in any jobs the same are sent as json to the user.
        joboffers = {
            "Desc ": "Available job offers for " + "'" + searchtext + "'"
        }
        #if the user's searchtext doesn't match any, the user receives no jobs message
        if not cursor.rowcount:
            joboffer = "Currently there are no job openings!"
        joboffers['jobs'] = joboffer
        return jsonify({'joboffers': joboffers})
Example #33
0
def applyjob():
    #when a user applies for a job, the user is notified via email and an entry is made in the database as job applcation.
    if request.method == 'POST':
        jobid = request.form['jobid']
        org = request.form['org']
        pos = request.form['pos']
        city = request.form['city']
        usermail = session['usermail']
        today = date.today()
        cursor = mysql.connection.cursor()
        try:
            cursor.execute(
                "SELECT status FROM appliedjobs WHERE jobid= % s and userid= % s",
                (
                    jobid,
                    usermail,
                ),
            )
            if cursor.rowcount:
                status = cursor.fetchone()
                msg = 'You have already applied for this job, and the status is ' + status[
                    0] + ' !'
                return render_template('main.html',
                                       msg=msg,
                                       joboffers=session['joboffers'])
            cursor.execute(
                "INSERT INTO appliedjobs(jobid,userid,status,appliedon) VALUES (% s, % s, % s, % s)",
                (jobid, usermail, 'pending', today))
            mysql.connection.commit()
            msg = 'Your application is received!'
            TEXT = f"""\
Hi {session['username']},

Thank you for applying to the role of {pos} at {org}. 

We are happy to announce that your application for the role of {pos}
at {org} is received. All further communication will be from {org}.
If you are among the qualified candidates, you will receive  communication
from  the recruiters of {org} to schedule a virtual interview. 

In any case, we will keep you posted on the  status of your application.
You can also check the status of your application from the profile section
of the website.

Application Details
Organization : {org}
Position : {pos}
Name    : {session['username']}
Email  for correspondence {usermail}.

Wishing you all the best and we hope you will land in your dream job soon.
Regards,
GetaJob Team.

This is a system generated email, please do not reply to this email.
            """
            SUBJECT = "Application Received!"
            sendmail(TEXT, usermail, SUBJECT)
        except Exception as e:
            print('Cannot add applied job to db or send mail to user', e)
            msg = 'A problem on our side, please try after sometime!'
    return render_template('main.html',
                           msg=msg,
                           joboffers=session['joboffers'])
Example #34
0
def register():
    #The data from the sign up form is collected and an account is created of the user.
    msg = ''
    if request.method == 'POST':
        usermail = request.form['usermail']
        if not re.match(r'[^@]+@[^@]+\.[^@]+', usermail):
            msg = 'Invalid email address !'
            return render_template('signup.html', msg=msg)
        tcCheck = request.form['tcCheck']
        if not tcCheck:
            #Checks user agreement to the terms and conditions.
            msg = 'You should Agree to our terms and conditions to proceed!'
            return render_template('signup.html', msg=msg)

        username = request.form['firstname'] + ' ' + request.form[
            'lastname']  #Name
        gender = request.form['gender']
        age = request.form['age']
        aboutme = request.form['aboutme']
        city = request.form['city']
        educ = request.form['NameOfGradInst'] + '!' + request.form[
            'gradGpa'] + '!' + request.form['gradDate'] + '!' + request.form[
                'NameofSscInst'] + '!' + request.form[
                    'sscGpa'] + '!' + request.form[
                        'sscDate'] + '!' + request.form[
                            'NameofHsclInst'] + '!' + request.form[
                                'HsclGpa'] + '!' + request.form['HsclDate']
        certIn = request.form['CertifiedAin']
        skillset = request.form['skillset']
        git = request.form['git']
        workedAt = request.form['workedAt']
        workExp = request.form['workExp']
        degree = request.form['degree']

        alphabet = string.ascii_letters + string.digits + '!' + '@' + '#' + '$' + '%' + '&' + '*'
        password = ''.join(secrets.choice(alphabet) for i in range(10))
        passhash = hashlib.md5(password.encode())
        passhash = passhash.hexdigest()
        #Instead of storing the password in plain text formate in the database, the password is hashed and the hash of the password is stored.
        cursor = mysql.connection.cursor()
        #checks if the user already has an account
        cursor.execute('SELECT * FROM login WHERE email = % s', (usermail, ))
        account = cursor.fetchone()
        if account:
            msg = 'This Email Address is already registered!'
            return render_template('signup.html', msg=msg)
        elif not re.match(r'[^@]+@[^@]+\.[^@]+', usermail):
            msg = 'Invalid email address !'
            return render_template('signup.html', msg=msg)
        else:
            try:
                cursor.execute(
                    "INSERT INTO user VALUES(% s, %s, % s, % s, %s, % s, % s, % s, % s, % s, % s, % s, % s,% s)",
                    (usermail, username, gender, age, aboutme, city,
                     educ, certIn, skillset, git, workedAt, workExp,
                     date.today(), degree))
                cursor.execute("INSERT INTO login VALUES (% s, % s)",
                               (usermail, passhash))
                mysql.connection.commit()
                msg = 'You are now registered with getAjob! Login to Continue. The password is sent to your mail.'
                TEXT = f"""\
Hi {username},

Welcome to getaJob, Thank you for registering with us. 
Your account is now actived. This confirmation is for your
records, and this mail also has the password that you will
use to login to the website. So, please retain this email.

Registration Details
Name     : {username}
Email    : {usermail}
Password : "******"

Wishing you all the best!
Regards,
GetaJob Team.

If you have any questions, including changes to your registration or 
cancellation of request. Please feel free to reply to this email.
                """
                SUBJECT = "GETaJob Registration"
                sendmail(TEXT, usermail, SUBJECT)
            except Exception as e:
                print('Inserting data into login or user table failed :', e)
                msg = 'A problem on our side, please try after sometime!'
                return render_template('signup.html', msg=msg)
    elif request.method == 'GET':
        msg = 'Please fill out the form !'
    #An email is sent to the user with login details and a message is displayed on the login form.
    return render_template('login.html', msg=msg)