def main(): failed_checks = [] checks = [(check_ram, "Error - Available memory is less than 500MB"), (check_root_full, "Error - Available disk space is less than 20%"), (check_no_network, "Error - localhost cannot be resolved to 127.0.0.1"), (check_cpu_constrained, "Error - CPU usage is over 80%")] everything_ok = True for check, msg in checks: if check(): print(msg) failed_checks.append(msg) everything_ok = False # sys.exit(1) if not everything_ok: email_body = "Please check your system and resolve the issue as soon as possible." email_subject = failed_checks sender = "*****@*****.**" recipient = "{}@example.com".format(lab_user) error_report = generate_error_report(sender, recipient, email_subject, email_body) send_email(error_report) #sys.exit(1) print("Everything ok.") sys.exit(0)
def main(): desc_dir = "supplier-data/descriptions/" desc_files = os.listdir(desc_dir) attachment = "/tmp/processed.pdf" title = "Processed on " + str( datetime.datetime.now().strftime("%Y-%m-%d")) + '\n' email_from = "*****@*****.**" email_to = "*****@*****.**" email_subject = "Upload Completed - Online Fruit Store" email_body = "All fruits are uploaded to our website successfully. A detailed list is attached to this email." supplier_data_list = [] for file in desc_files: fruit_data = {} with open(desc_dir + file) as f: fruit_data['name'] = f.readline().rstrip('\n') fruit_data['weight'] = f.readline().rstrip('\n') supplier_data_list.append(fruit_data) report = reports.generate_report(attachment, title, generate_paragraph(supplier_data_list)) emails.send_email( emails.generate_email(email_from, email_to, subject_line, email_body, attachment))
def action(self, resource, context, form): email = form['email'].strip() # 1. Make the user, or get it results = context.database.search(format='user', email=email) if len(results) == 0: # New user user = context.root.make_user() for name in self.fields: field = self.get_field(name) if field and getattr(field, 'persistent', True): self.set_value(user, context, name, form) user.update_pending_key() email_id = 'user-ask-for-confirmation' else: # User already registered user = results.get_resources().next() email_id = 'register-already-registered' # 2. Send email send_email(email_id, context, email, user=user) # 3. Show message message = MSG( u'<div id="registration-end-msg">' u'An email has been sent to you, to finish the registration ' u'process follow the instructions detailed in it.</div>') return message.gettext().encode('utf-8')
def main(): subject = health() body = "Please check your system and resolve the issue as soon as possible." email = emails.generate_email("*****@*****.**", "*****@*****.**", subject, body, None) emails.send_email(email)
def send_warning(subject): sender = '*****@*****.**' receiver = "{}@example.com".format(os.environ["USER"]) body = 'Please check your system and resolve the issue as soon as possible.' message = emails.generate_email(sender, receiver, subject, body) emails.send_email(message) return None
def send(): msg='Name:'+request.form['name']+' Email: '+request.form['email']+' Message:'+request.form['message'] try: send_email(request.form['subject'],msg) return "OK" except: return "Ваш email не отправлен. Пожалуйста попробуйте позвонить нам!"
def report_issue(issue): sender = "*****@*****.**" recipient = "*****@*****.**" subject = issue body = "Please check your system and resolve the issue as soon as possible." message = emails.generate_email(sender, recipient, subject, body) emails.send_email(message)
def check_localhost(): '''hostname "localhost" cannot be resolved to "127.0.0.1"''' if socket.gethostbyname("localhost") != "127.0.0.1": host_email = generate_email( sender, receiver, "Error - localhost cannot be resolved to 127.0.0.1", email_body) send_email(host_email)
def send_email(subject): user = os.getenv('USER') sender = '*****@*****.**' receiver = '{}@example.com'.format(user) body = 'Please check your system and resolve the issue as soon as possibl email = emails.generate_report(sender, receiver, subject, body) emails.send_email(email)
def send_mail(subject, body, attachment=None): sender = "*****@*****.**" receiver = "{}@example.com".format(os.environ.get('USER')) message = emails.generate_email(sender, receiver, subject, body, attachment) emails.send_email(message)
def action(self, resource, context, form): # Check register key key = resource.get_property('user_state').get_parameter('key') if not key: context.message = MSG(u'User is not pending') return if form['key'] != key: context.message = messages.MSG_BAD_KEY return # Check passwords password = form['newpass'] password2 = form['newpass2'] if password != password2: context.message = messages.MSG_PASSWORD_MISMATCH return # Set user resource.set_value('password', password) resource.del_property('user_state') # Set cookie resource._login(password, context) # Send email to_addr = resource.get_value('email') send_email('register-send-confirmation', context, to_addr, user=resource) # Ok message = INFO(u'Operation successful! Welcome.') return context.come_back(message, goto='./')
def response(): receipt2 = request.args.get('orderRef') if receipt2 is not None: session['premium'] = 2 subid = session['subid'] ordid = session['orderid'] ordercreate = datetime.date.today() ordexp = ordercreate + dateutils.relativedelta(months=session['mcmonths']) existquer = Order.query.filter_by(cust_id=session['userid']).first() if existquer is not None: updorder = update(Order).where(Order.cust_id == session['userid']).values(orderl_expire=ordexp, sub_id=int(subid), ordernumber=int(ordid)) db.session.execute(updorder) db.session.commit() send_email('Din ordrereferanse fra Gameserver.no', ADMINS[0], session['email'], render_template('receipt.txt', subid=str(subid), ordid=str(ordid), ordexp=str(ordexp), orderref=receipt2, totprice=session['mcprice']), render_template('receipt.html', subid=str(subid), ordid=str(ordid), ordexp=str(ordexp), orderref=receipt2, totprice=session['mcprice'])) return render_template('response.html', receipt=receipt2, subid=subid, totprice=session['mcprice'], ordid=ordid, ordexp=ordexp) else: order = Order(int(session['portid']), int(subid), int(ordid), ordercreate, ordexp, '1', int(session['userid'])) db.session.add(order) db.session.commit() send_email('Din ordrereferanse fra Gameserver.no', ADMINS[0], session['email'], render_template('receipt.txt', subid=str(subid), ordid=str(ordid), ordexp=str(ordexp), orderref=receipt2, totprice=session['mcprice']), render_template('receipt.html', subid=str(subid), ordid=str(ordid), ordexp=str(ordexp), orderref=receipt2, totprice=session['mcprice'])) return render_template('response.html', receipt=receipt2, subid=subid, totprice=session['mcprice'], ordid=ordid, ordexp=ordexp) else: return render_template('response.html', receipt='Din bestilling er avbrutt')
def send_error_message(subject): sender = '*****@*****.**' recepient = '*****@*****.**' message = emails.generate_email(sender, recepient, subject, 'Please check your system and resolve the issue as soon as possible.') emails.send_email(message) print('Message sent')
def email_warning(error): sender = "*****@*****.**" receiver = "{}@example.com".format(os.environ["USER"]) subject = error body = "Please check your system and resolve the issue as soon as possible." message = emails.generate_email(sender, receiver, subject, body) emails.send_email(message)
def register(): user = {} user["phone"] = request.form["phone"] user["phone_carrier"] = request.form["phonecarrier"] user["email"] = request.form["email"] user["pwd"] = request.form["password"] user["first_name"] = request.form["firstname"] user["last_name"] = request.form["lastname"] passwordconfirm = request.form["passwordconfirm"] verification_address = hashlib.sha224(user["email"] + app.config["SECRET_KEY"]).hexdigest() user["verification_address"] = verification_address # Email client to complete registration subject = "Complete Your WamBam! Registration" recipients = [user["email"]] #Text version of email to send to activate account body = "Welcome to WamBam!<br><br>You're almost good to go." + \ " Just follow this link to activate your account: http://wambam.herokuapp.com/v/"+ \ verification_address + "<br><br>Yours truly,<br>The WamBam! Team" #HTML version html = "<div style='background: #0F4D92; color: white; font-size:20px; padding-top: 10px;" + \ " padding-bottom: 10px; padding-left: 20px'> WamBam! </div><br>" + \ " <div style='padding-left: 20px'>" + \ body + \ "</div>" emails.send_email(subject, recipients, body, html) wambam_user.add_user(user) return redirect("/login", code=307)
def email_warning(error): sender = "*****@*****.**" #placeholder for sender receiver = "*****@*****.**" #placeholder for receiver subject = error body = "Please check system and resolve issue as soon as possible. Thank you." message = emails.generate_email(sender, receiver, subject, body) emails.send_email(message)
def send_email(subject): email = emails.generate_email( "*****@*****.**", "*****@*****.**", subject, "Please check your system and resolve the issue as soon as possible.", "") emails.send_email(email)
def process(self, line): entry = self.decode(line) for fn in self.fns: try: yield from fn(entry) except Exception as e: send_email(fn.owners, e)
def communicate(failures, to_insert, total_detected, testmode, date): active_jobs = seta.get_distinct_tuples() format_in_table(active_jobs, to_insert) # we may need to fix this later percent_detected = ((len(total_detected) / (len(failures) * 1.0)) * 100) print "We will detect %.2f%% (%s) of the %s failures" % \ (percent_detected, len(total_detected), len(failures)) if testmode: return prepare_the_database() insert_in_database(to_insert, date) if date is None: date = datetime.date.today() change = print_diff("%s" % (date - datetime.timedelta(days=1)).strftime('%Y-%m-%d'), '%s' % date.strftime('%Y-%m-%d')) try: total_changes = len(change) except TypeError: total_changes = 0 if total_changes == 0: send_email(len(failures), len(to_insert), date, "no changes from previous day", admin=True, results=False) else: send_email(len(failures), len(to_insert), date, str(total_changes) + " changes from previous day", change, admin=True, results=True)
def alert(subject): sender = "*****@*****.**" receiver = "{}@example.com".format(os.environ.get('USER')) body = "Please check your system and resolve the issue as soon as possible." message = emails.generate_email(sender, receiver, subject, body) emails.send_email(message)
def main(): checks = [ (check_cpu_constrained, 'Error - CPU usage is over 80%'), (check_disk_storage, 'Error - Available disk space is less than 20%'), (check_available_RAM, 'Error - Available memory is less than 500MB'), (check_host, 'Error - localhost cannot be resolved to 127.0.0.1'), ] everything_ok = True for checkIsGood, msg in checks: if checkIsGood is False: email = generate_alert_email( sender='*****@*****.**', recipient= '*****@*****.**', #UPDATE WITH LAB [email protected] subject=msg, body= 'Please check your system and resolve the issue as soon as possible.' ) send_email(email) print("Alert sent successfully") everything_ok = False if not everything_ok: sys.exit(1) else: print("Everything ok.") sys.exit(0)
def generate_and_send_email(subject): """ constructs and sends email """ sender = "*****@*****.**" to = "*****@*****.**" body = "Please check your system and resolve the issue as soon as possible." msg = emails.generate_email(sender, to, subject, body) emails.send_email(msg)
def send_email(subject): email = emails.generate_email( "", "Please check your system and resolve hte issue as soon as possible", subject, "*****@*****.**", "*****@*****.**") emails.send_email(email)
def email_warning(error): sender = "*****@*****.**" recipient = '*****@*****.**' subject = error body = "Please check your system and resolve the issue as soon as possible." message = emails.generate_error_report(sender, recipient, subject, body) emails.send_email(message)
def run(): desc_dir = "supplier-data/descriptions/" # This works only when in directory "Python Coding/6 Automating Real-World Tasks with Python/Project 4/" desc_list = os.listdir(desc_dir) formatted_date = datetime.date.today().strftime("%B %d, %Y") fruit_paragraph = "" report_path = "/tmp/processed.pdf" for desc in desc_list: desc_with_path = desc_dir + desc with open(desc_with_path) as file: line = file.readline() fruit_paragraph += "name: " + line.rstrip("\n") + "<br/>" line = file.readline() fruit_paragraph += "weight: " + line.rstrip("\n") + "<br/><br/>" reports.generate_report(report_path, "Processed Update on " + formatted_date, fruit_paragraph) # Send the PDF report as an email attachment message = emails.generate_email( "*****@*****.**", "{}@example.com".format(os.environ.get('USER')), "Upload Completed - Online Fruit Store", "All fruits are uploaded to our website successfully. A detailed list is attached to this email.", report_path ) emails.send_email(message)
def error_mail(sub): sender = "*****@*****.**" receipient = "*****@*****.**" subject=sub body="Please check your system and resolve the issue as soon as possible." message=emails.generate_error_email(sender,receipent,subject,body) emails.send_email(message)
def process(log, triggers, line): entry = log.decode(line) for trigger in triggers: try: yield from trigger.digest(entry) except Exception as e: send_email(trigger.owners, e)
def email_alert(subject): sender = "*****@*****.**" recipient = "*****@*****.**" body = "Please check your system and resolve the issue as soon as possible." attachment_path = "" message = emails.generate_email(sender, recipient, subject, body, attachment_path) emails.send_email(message)
def main(): """Make it do what it do.""" email_list = [] try: chk_cpu() except AssertionError as error: print('adding email to queue') collector['subject'] = error.args[0] email_list.append(list(collector.values())) try: chk_storage() except AssertionError as error: print('adding email to queue') collector['subject'] = error.args[0] email_list.append(list(collector.values())) try: chk_memory() except AssertionError as error: print('adding email to queue') collector['subject'] = error.args[0] email_list.append(list(collector.values())) try: chk_server() except AssertionError as error: print('adding email to queue') collector['subject'] = error.args[0] email_list.append(list(collector.values())) for message in email_list: msg = emails.generate_email(message[0], message[1], message[2], message[3]) emails.send_email(msg)
def send_email(subject): email = emails.generate_email( "*****@*****.**", "*****@*****.**", subject, "Please check your system and resolve the issue as soon as possible.", "") emails.send_email(email) # If there's not enough disk, or not enough CPU, print an error if not check_cpu_usage(): subject = "Error - CPU usage is over 80%" print(subject) send_email(subject) if not check_memory_usage(): subject = "Error - Available memory is less than 500MB" print(subject) if not check_disk_usage('/'): subject = "Error - Available disk space is less than 20%" print(subject) send_email(subject) if not check_localhost(): subject = "Error - localhost cannot be resolved to 127.0.0.1" print(subject) send_email(subject)
def main(argv): attachment = '/tmp/processed.pdf' today = datetime.date.today() title = today.strftime("Processed update on %B %d, %Y") description_list = [] description_directory = '/home/student-00-72706b664a64/supplier-data/descriptions/' for file in os.listdir(description_directory): with open(description_directory + '/' + file, 'r') as description_file: description_files = [] for line in description_file: description_files.append(line) description_list.append('name: ' + description_files[0].capitalize() + '<br/>') description_list.append('weight: ' + description_files[1] + '<br/>') description_list.append('<br/>') paragraph = ' '.join(description_list) print(paragraph) reports.generate_report(attachment, title, paragraph) recipient = "{}@example.com".format(os.environ.get('USER')) body = 'All fruits are uploaded to our website successfully. A detailed list is attached to this email.' message = emails.generate_email('*****@*****.**', recipient, "Upload Completed - Online Fruit Store", body, attachment) emails.send_email(message)
def warn(): """Get and post warnings by zip code""" html = render_template("warning.html", name="Marcus", warn="Winter Storm") send_email(html, "*****@*****.**", "Warning!!") response = jsonify({'data': 'success'}) response.status_code = 200 return "hello"
def register(): """Api route for validating and saving Our users into database Additionalyl sends email and text upon User creations """ form = UserForm(csrf_enabled=False) if form.validate(): new_user = User.create(first_name=form.first_name.data, email=form.email.data, phone_number=form.phone_number.data) response = jsonify( {'success': form.first_name.data, 'message': 'Success'}) html = render_template("welcome.html", name=new_user.first_name) send_email(html, new_user.email) if new_user.phone_number == os.environ.get("PHONE"): send_async_sms("Welcome To Ready for it!") new_user.delete() response.status_code = 201 return response response = jsonify({'error': 'Failed', 'message': form.errors}) response.status_code = 400 return response
def signup(): form = SignUpForm() if request.method == 'POST' and form.validate_on_submit(): signup = SignUp("", "", "", "", False, False, True) signup.name = form.name.data signup.email = form.email.data signup.school = form.school.data signup.experience = form.experience.data db.session.add(signup) db.session.commit() mail_body = render_template('mails/signup_thankyou.txt') send_email("Graffathon - Ilmoittautuminen rekisteröity", [form.email.data], mail_body, "") return redirect(url_for('signup_thank_you')) # 66 = maximum visitors we take MAX_VISITORS = 66 places = {'min': MAX_VISITORS - SignUp.query.filter_by(visible=True, confirmed=True).count(), 'max': MAX_VISITORS - SignUp.query.filter_by(visible=True, paid=True).count()} return render_template('signup.html', form=form, places=places)
def send(self): """ Send the assembled log out as an email. """ body = '\n'.join(self.log) recipient = ACCOUNTING_MAIL_RECIPIENT subject = 'Batch run' send_email(body=body, recipient=recipient, subject=subject)
def email_confirmation(user, payload): """ """ subject = "[adamOwes] - confirm email" recipients = [user.email] text_body = render_template("emails/email_confirmation.txt", user=user, payload=payload) html_body = render_template("emails/email_confirmation.html", user=user, payload=payload) send_email(subject, recipients, text_body, html_body) return True
def email_password_reset(user, payload): """ """ subject = "[adamOwes] - password reset" recipients = [user.email] text_body = render_template("emails/password_reset.txt", user=user, payload=payload) html_body = render_template("emails/password_reset.html", user=user, payload=payload) send_email(subject, recipients, text_body, html_body) return True
def save_info(organisation, email_address): key = str(uuid.uuid4()) info = db.session.query(User.github_username, User.name).filter_by(organisation = organisation).all() if(info == []): # Another entry in the queue could have updated the DB items = get_nodes.main(organisation) org = Organisation(organisation) db.session.add(org) for i in items: usr = User(organisation,i.name,i.github_username) db.session.add(usr) db.session.commit() emails.send_email(organisation, [email_address]) return key
def send_notifications_strotimer(): start_time = datetime.datetime.now() + datetime.timedelta(days=1) end_time = datetime.datetime.now() + datetime.timedelta(days=1, hours=1) data = { 'start_time': start_time.strftime('%Y-%m-%dT%H:00:00'), 'end_time': end_time.strftime('%Y-%m-%dT%H:00:00') } auth_token_cookie = make_superuser_auth_cookie() cookies = dict(request.cookies.items() + auth_token_cookie.items()) headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} response = requests.post(strotime_notifications_uri, data=json.dumps(data), cookies=cookies, headers=headers) if response.status_code == 201: strotime_slots = json.loads(response.content) for strotime_slot in strotime_slots: email_address = strotime_slot['email_address'] resource_name = strotime_slot['resource_name'] person_name = strotime_slot['person_name'] old_date_format = '%Y-%m-%dT%H:%M:%S' new_date_format = '%Y-%m-%d %H:%M:%S' start_time = datetime.datetime.strptime(strotime_slot['start_time'], old_date_format) start_time = start_time.strftime(new_date_format) end_time = datetime.datetime.strptime(strotime_slot['end_time'], old_date_format) end_time = end_time.strftime(new_date_format) if start_time is not None and \ end_time is not None and \ email_address is not None and \ resource_name is not None and \ person_name is not None: logger.info("Email address: " + email_address) logger.info("Resource name: " + resource_name) logger.info("Person name: " + person_name) logger.info("Start time: " + start_time) logger.info("End time: " + end_time) message = render_template("email_strotime_notification.txt", start_time=start_time, end_time=end_time, resource_name=resource_name, person_name=person_name) if message is not None: logger.info(message) send_email(u'Påminnelse på strøtime', u'*****@*****.**', [email_address], message) else: logger.error("Missing required data.")
def signup(): if g.user is not None and g.user.is_authenticated(): return redirect(url_for('index')) form = SignupForm() if form.validate_on_submit(): nick = form.username.data us = User.query.filter_by(nickname = nick).first() print us if us is None: pass_hash = md5(form.password.data).hexdigest() send_email(subject=u'Założenie konta na Candeli', sender = 'grzegorz.parka', recipients = [form.email.data], text_body = render_template('account_creation_mail.txt', nick = nick, password_hash = pass_hash), html_body = render_template('account_creation_mail.html', nick = nick, password_hash = pass_hash)) flash(u"""Wysłaliśmy Ci maila z linkiem aktywacyjnym. Sprawdź swoją skrzynkę wydziałową :)""") pending_user = Registration(nickname = form.username.data, password = unicode(pass_hash), email = form.email.data, salt = 'a') db.session.add(pending_user) db.session.commit() else: flash(u"""Nie możesz wybrać tej nazwy użytkownika. Użytkownik już istnieje.""") nickname = request.args.get("username") password = request.args.get("pass") if nickname and password: pending_user = Registration.query.filter_by(nickname = nickname).first() if pending_user.password == password: flash(u"""Witaj na Candeli! Teraz zaloguj się używając wybranej przy rejestracji nazwy użytkownika oraz hasła.""") user = User(nickname = nickname, password = unicode(password), email = pending_user.email) db.session.add(user) db.session.delete(pending_user) db.session.commit() return redirect(url_for('login')) else: flash(u"""Niewłaściwe dane użytkownika.""") return render_template('signup.html', title = u'Zarejestruj się', form = form)
def GET(self, resource, context): # Already confirmed user_state = resource.get_value('user_state') if user_state != 'pending': msg = MSG(u'User has already confirmed his registration!') return context.come_back(msg) # Resend confirmation resource.update_pending_key() email = resource.get_value('email') send_email('user-ask-for-confirmation', context, email, user=resource) # Ok msg = MSG(u'Confirmation sent!') return context.come_back(msg)
def php_post(): #send_email(subject, fullname, "*****@*****.**", message, "<b>HTML</b> body") # 'request' defined by import package if request.method == 'POST': firstname = request.form['firstname'] lastname = request.form['lastname'] email = request.form['email'] message = request.form['message'] print "first in /php_post: " + firstname print "last in /php_post:: " + lastname print "email in /php_post:: " + email print "message in /php_post:: " + message #match = re.search(r'word:\w\w\w', str) nameregex = re.compile("^[a-zA-Z\-]+$") firstmatch = nameregex.match(firstname) #firstmatch = re.search(r'[a-zA-Z\-]', firstname) lastmatch = nameregex.match(lastname) emailregex = re.compile("[a-zA-Z0-9_\.\+\-]+@[a-zA-Z0-9_\.\+\-]+\.[a-zA-Z]{3}$") emailmatch = emailregex.match(email) print firstmatch print lastmatch print emailmatch if len(firstname) == 0 or firstmatch is None: print "bad first name input" return render_template("contact.html", error = "Invalid first name") elif len(lastname) == 0 or lastmatch is None: print "bad last name input" return render_template("contact.html", error = "Invalid last name") elif len(email) == 0 or emailmatch is None: print "bad email input" return render_template("contact.html", error = "Invalid email") elif len(message) == 0: print "bad message input" return render_template("contact.html", error = "Invalid message") else: # Python email fullname = firstname + " " + lastname subject = "Personal Website Message from " + fullname + ", " + email send_email(subject, fullname, "*****@*****.**", message, "") dictionary = {'firstname': firstname, 'lastname':lastname, 'email':email, 'message':message} print "posting to php" #requests.post("http://localhost/PersonalSite/app/templates/index.php", data=dictionary) #requests.post("http://ksum.herokuapp.com/app/templates/index.php", data=dictionary) requests.post("http://ksumdb.herokuapp.com/index.php", data=dictionary) return render_template("contact.html", first = firstname, last = lastname)
def send_email(): """ 邮件发送 """ try: from emails import send_email msg = 'This is a test email!' send_email( subject=u'邮件主题', sender=(u'系统邮箱', '*****@*****.**'), recipients=[(u'尊敬的用户', '*****@*****.**')], html_body=render_template('email.html', message=msg) ) return jsonify({'success': u'邮件发送成功'}) except Exception, e: return jsonify({'error': e.message})
def make_new_resource(self, resource, context, form): proxy = super(Users_AddUser, self) child = proxy.make_new_resource(resource, context, form) # Send email to the new user if child: if form['password']: email_id = 'add-user-send-notification' else: child.update_pending_key() email_id = 'user-ask-for-confirmation' send_email(email_id, context, form['email'], user=child) # Ok return child
def vtresponse(): orderref = request.args.get('orderRef') slots = session['slots'] price = session['price'] months = session['months'] serv = Server() userid = session['userid'] user = session['username'] openport = VoicePort.query.filter_by(port_used=2).first() expire = datetime.date.today() + dateutils.relativedelta(months=int(months)) existvent = VtOrder.query.filter_by(cust_id=session['userid']).first() if orderref is not None and existvent is not None: extramonths = existvent.expiration + dateutils.relativedelta(months=int(months)) stmt = update(VtOrder).where(VtOrder.cust_id == session['userid']).values(expiration=extramonths).values(slots=slots) db.session.execute(stmt) db.session.commit() #server, user, key, value serv.editventprops(str(ventserver.server_ip), user, str("port"), str(openport.port_no)) serv.editventprops(str(ventserver.server_ip), user, str("maxclients"), str(slots)) send_email('Din ordrereferanse fra Gameserver.no', ADMINS[0], session['email'], render_template('receiptvt.txt', subid=str(orderref), ordexp=str(months), slots=str(slots), totprice=session['price'], orderexp=expire), render_template('receiptvt.html', subid=str(orderref), ordexp=str(months), slots=str(slots), totprice=session['price'], orderexp=expire)) return render_template('vtresponse.html', orderref=orderref, slots=slots, price=price, months=months, ordexp=expire) elif orderref is not None: vtadd = VtOrder(slots, price, expire, openport.port_id, userid) stmt = update(Port).where(Port.port_id == openport.port_id).values(port_used=1) db.session.execute(stmt) db.session.add(vtadd) db.session.commit() serv.sendvent(ventserver.server_ip, user) serv.deployvent(user, 'ventpro.zip', ventserver.server_ip) serv.editventprops(str(ventserver.server_ip), user, str("port"), str(openport.port_no)) serv.editventprops(str(ventserver.server_ip), user, str("maxclients"), str(slots)) userstm = update(User).where(User.cust_id == session['userid']).values(role=2) db.session.execute(userstm) db.session.commit() session['premium'] = 2 send_email('Din ordrereferanse fra Gameserver.no', ADMINS[0], session['email'], render_template('receiptvt.txt', subid=str(orderref), ordexp=str(months), slots=str(slots), totprice=session['price'], orderexp=expire), render_template('receiptvt.html', subid=str(orderref), ordexp=str(months), slots=str(slots), totprice=session['price'], orderexp=expire)) return render_template('vtresponse.html', orderref=orderref, slots=slots, price=price, months=months, ordexp=expire) else: return render_template('vtresponse.html', orderref=orderref, slots=slots, price=price, months=months)
def contact(): if request.method == 'POST': contact = m.Contact( issue_type=request.form['issue_type'], email=request.form['email'], comment=request.form['comment'] ) email_message = contact['comment'] emails.send_email('RcrdKeeper Registration Confirmation', app.config['MAIL_USERNAME'], app.config['MAIL_USERNAME'], email_message) return render_template('contact.html')
def register(): json_data = request.json data=get_static_json_file("users.json") key=json_data["given_name"]+" "+json_data["family_name"]+" <"+json_data["email"]+">" if key in data: status = 'this user is already registered' else: data[key] = json_data data[key]["confirmed"]=False with open(ret_url("users.json", "/json"), "w") as file: json.dump(data, file, indent=4) status = True token = generate_confirmation_token(json_data["email"]) confirm_url = url_for('confirm_email', token=token, _external=True) html = render_template('authentication/registration_email.html', confirm_url=confirm_url) subject = "Please confirm your email" send_email(json_data["email"], subject, html) return jsonify({'result': status})
def index(): form = ContactForm() if request.method == 'POST': if form.validate() == False: flash('All fields are required.') flash_errors(form) return redirect(url_for('index')) else: x=models.User(name=form.name.data,email=form.email.data,subject=form.subject.data,message=form.message.data) db.session.add(x) db.session.commit() subject=form.subject.data message=form.name.data+' said '+form.message.data+" form "+form.email.data send_email(subject,'doesitmatter',['*****@*****.**'],message) flash('Thank you for your message') flash_errors(form) return redirect(url_for('index')) elif request.method == 'GET': return render_template('index.html', form=form) # @app.route("/contact", methods=['GET', 'POST']) # def contact(): # form = ContactForm() # if request.method == 'POST': # if form.validate() == False: # flash('All fields are required.') # return redirect(url_for('index')) # else: # return 'Form posted.' # elif request.method == 'GET': # return render_template('index.html', form=form) # from emails import follower_notification # @app.route('/follow/<nickname>') # @login_required # def follow(nickname): # user = User.query.filter_by(nickname = nickname).first() # # ... # follower_notification(user, g.user) # return redirect(url_for('user', nickname = nickname))
def signup(): form = signup_form(request.form) if request.method == 'POST' and form.validate(): olduser = User.query.filter_by(cust_username=form.username.data).first() newuser = form.username.data newmail = form.email.data oldmaildb = User.query.filter_by(cust_mail=newmail).first() oldmail = "" if oldmaildb != None: oldmail = oldmaildb.cust_mail if (str(newuser) != str(olduser)) and (str(newmail) != str(oldmail)): if re.match(r"^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]*$", form.email.data): if form.phone.data == "" or form.phone.data.isdigit(): if not re.search(r'[\s]', newuser): user = User(form.username.data, form.password.data, form.email.data, form.fname.data, form.lname.data, form.phone.data) db.session.add(user) db.session.commit() flash('Takk for at du registrerte deg!') send_email('Velkommen til Gameserver.no!', ADMINS[0], form.email.data, render_template('velkommen.txt', username = form.username.data, password = form.password.data, email=form.email.data, fname=form.fname.data, lname=form.lname.data, phone=form.phone.data), render_template('velkommen.html', username = form.username.data, password = form.password.data, email=form.email.data, fname=form.fname.data, lname=form.lname.data, phone=form.phone.data)) return redirect(url_for('login')) else: flash('Brukernavn kan ikke inneholde mellomrom!') return render_template('signup.html', form=form) else: flash('Telefonnummeret er ikke gyldig!') return render_template('signup.html', form=form) else: flash('Ugyldig e-post!') return render_template('signup.html', form=form) else: flash('Brukernavn eller e-post finnes allerede!') return render_template('signup.html', form=form) else: return render_template('signup.html', form=form)
def forgot(): if request.method == 'POST': email_exist = m.User.get(email=request.form['email']) if email_exist: key = hashlib.md5(email_exist['id']).hexdigest() user = m.User.get(id=email_exist['id']) user.key = key user.save() email_message = 'This email has receieved a request to reset password for RcrdKeeper. Follow the below link to reset rcrdkeeper.com/reset/' + key emails.send_email('RcrdKeeper Account Recovery', app.config['MAIL_USERNAME'], email_exist['email'], email_message) return None
def is_expired(**kwargs): q_list = query_all(member_table) today = datetime.now().date() fourweeks = timedelta(days=14) for dict in q_list: expires = datetime.strptime(dict['expires'],"%Y-%m-%d") delete_fil = (expires + fourweeks).date() if expires.date() - today == timedelta(days=14): with Mdb.test_request_context("/"): send_email("Your CUAS membership will expire in two weeks!", Mdb.config['ADMINS'][0], [str(dict['email'])], render_template("will_expire_email.txt",member=str(dict['first_name']))) if today == expires.date(): with Mdb.test_request_context("/"): send_email("Your CUAS membership has expired!", Mdb.config['ADMINS'][0], [str(dict['email'])], render_template("expired_email.txt",member=str(dict['first_name']))) if today > delete_fil: email_search = member_table.query.filter_by(email=dict['email']).first() if email_search: db.session.delete(email_search) write_deleted_log(dict) print "%s has been deleted from member table. Membership expired on %s. Log here: %s" % (' '.join([dict['first_name'],dict['last_name']]),expires.date(),"/Users/mjohns44/Code/GIT/Mdb/logs/delete.log") db.session.commit()
def action(self, resource, context, form): # Get the user loginname = form['loginname'].strip() user = context.root.get_user_from_login(loginname) # Case 1: Forgotten password if form['no_password']: # 1.1 Send email if user: email = user.get_value('email') if user.get_value('user_state') == 'invalid': email_id = None # TODO else: user.update_pending_key() email_id = 'forgotten-password-ask-for-confirmation' else: email_id = None # TODO Which is the email address? if email_id: send_email(email_id, context, email, user=user) # 1.2 Show message (we show the same message even if the user # does not exist, because privacy wins over usability) path = '/ui/website/forgotten_password.xml' handler = context.get_template(path) return stl(handler) # Case 2: Login if user is None: context.message = MSG_LOGIN_WRONG_NAME_OR_PASSWORD return error = user._login(form['password'], context) if error: context.message = error return return self.get_goto(user)
def register(): error = None if request.method == 'POST': user_exist = m.User.get(email=request.form['email']) if user_exist: error = "Account with this email already exist. \ Click 'forgot password' to recover your account." return render_template('login.html', error=error) else: hash_pw = generate_password_hash( request.form['register_password']) new_user = m.User() new_user.name = request.form['name'] new_user.email = request.form['email'] new_user.password = hash_pw new_user.birthdate = request.form['birthdate'] new_user.key = None new_user.save() email_message = 'Thank you for registering with RcrdKeeper. No further action is required to use your account.' session['user'] = new_user['id'] succ = 'Account successfully created. You are now logged in. \ You will recieve a confirmation email shortly.' emails.send_email('RcrdKeeper Registration Confirmation', app.config['MAIL_USERNAME'], request.form['email'], email_message) return render_template('home.html', succ=succ, first_login=True)
def action_switch_state(self, resource, context, form): # Verify if after this operation, all is ok usernames = form['ids'] if context.user.name in usernames: context.message = ERROR(u'You cannot change your state yourself.') return database = resource.database for username in usernames: user = database.get_resource('/users/%s' % username) email = user.get_value('email') user_state = user.get_value('user_state') if user_state == 'active': user.set_value('user_state', 'inactive') send_email('switch-state-deactivate', context, email) elif user_state == 'inactive': user.set_value('user_state', 'active') send_email('switch-state-activate', context, email) else: # pending continue # Ok context.message = messages.MSG_CHANGES_SAVED
def submit(): #Redirect user to home page if they did not specify a location that task is to occur at. if not ("lat" in session) or not ("lng" in session): return redirect(url_for("home")) title = request.form["title"] bid = request.form["bid"] bid = bid.replace("$",""); expiration = request.form["expiration"] #format for timedelta is (days, seconds, microseconds, #milliseconds, minutes, hours, weeks) expirationdate = datetime.datetime.now() if (expiration == "30min"): expirationdate += datetime.timedelta(0,0,0,0,30) elif (expiration == "1hr"): expirationdate += datetime.timedelta(0,0,0,0,0,1) elif (expiration == "1day"): expirationdate += datetime.timedelta(1) elif (expiration == "1wk"): expirationdate += datetime.timedelta(0,0,0,0,0,0,1) requestor_id = int(current_user.get_id()) #Encrypt user data encrypted = encryption.encrypt_dictionary(request.form) lat_encrypted = encryption.encrypt_string(session["lat"]) lng_encrypted = encryption.encrypt_string(session["lng"]) bid_encrypted = encryption.encrypt_string(bid) #Create task object task = schema.Task( requestor_id=requestor_id, latitude = lat_encrypted, longitude = lng_encrypted, short_title=encrypted["title"], bid=bid_encrypted, expiration_datetime=expirationdate, long_title=encrypted["description"], delivery_location=encrypted["location"], status="unassigned") db.session.add(task) db.session.commit() del session["lat"] del session["lng"] # Get logged in user first_name = encryption.decrypt_string(current_user.first_name) last_name = encryption.decrypt_string(current_user.last_name) # Get phone info for requester phone_number = encryption.decrypt_string(current_user.phone) phone_carrier = encryption.decrypt_string(current_user.phone_carrier) text_recipient = map(getTextRecipient, [phone_number], [phone_carrier]) # Construct confirmation message for requester msg_subject = "Order Submitted" msg_body = "Your task request for '" + title + \ "' has been placed! We'll text you when someone claims your task." # Send text message to requester asynchronously if request.referrer and request.referrer != '/test': emails.send_email(msg_subject, text_recipient, msg_body, msg_body) # Send alert text to all online fulfillers fulfillers = schema.Account.query.filter(schema.Account.online == True).all() def getPhone(fulfiller): return encryption.decrypt_string(fulfiller.phone) def getPhoneCarrier(fulfiller): return encryption.decrypt_string(fulfiller.phone_carrier) fulfiller_phones = map(getPhone, fulfillers) fulfiller_carriers = map(getPhoneCarrier, fulfillers) text_fulfillers = map(getTextRecipient, fulfiller_phones, fulfiller_carriers) # Remove task requestor from list of potential fulfillers if text_recipient[0] in text_fulfillers: text_fulfillers.remove(text_recipient[0]) if len(text_fulfillers) > 0: # Construct message for potential fulfillers msg_subject = "New Task Alert" msg_body = first_name + " " + last_name + " has created a task for '" + title + \ "'. Click the following link for more details: " + \ "http://wambam.herokuapp.com/viewtaskdetails/" + str(task.id) + " ." # Send text message to potential fulfillers if request.referrer and request.referrer != '/test': emails.send_email(msg_subject, text_fulfillers, msg_body, msg_body) return redirect("/confirm")
def claim(): #Get task that was claimed task_num = int(request.form["id"]) task = schema.Task.query.get(task_num) #Someone beat the potential fulfiller to the task! if (task.status != "unassigned"): return redirect("/sorry") decrypted_task = encryption.decrypt_object(task) title = decrypted_task["short_title"] location = decrypted_task["delivery_location"] bid = float(decrypted_task["bid"]) expiration = schema.dump_datetime(task.expiration_datetime) description = decrypted_task["long_title"] # Get fulfiller fulfiller = current_user decrypted_fulfiller = encryption.decrypt_object(fulfiller) # Get requester current_task = schema.Task.query.get(task_num) requestor_id = current_task.requestor_id requestor = schema.Account.query.get(requestor_id) decrypted_requestor = encryption.decrypt_object(requestor) email = decrypted_requestor["email"] # add entry to account_task table conn = engine.connect() results = conn.execute(schema.account_task.insert(), account_id=fulfiller.id, task_id=task_num, status="active") # update task table temp = schema.Task.query.get(int(task_num)) temp.status = "in_progress" # commit changes db.session.commit() # Get information on fulfiller to send confirmation text. fulfiller_number = decrypted_fulfiller["phone"] fulfiller_carrier = decrypted_fulfiller["phone_carrier"] text_fulfiller = getTextRecipient(fulfiller_number, fulfiller_carrier) # Construct message to send to fulfiller msg_subject = "Task Claimed" msg_body = "You have claimed the task '" + title + "'. Get in touch with " + \ decrypted_requestor["first_name"] + " " + decrypted_requestor["last_name"] + \ " at " + decrypted_requestor["phone"] + "." # Send message to fulfiller if request.referrer and request.referrer != '/test': emails.send_email(msg_subject, [text_fulfiller], msg_body, msg_body) # Get information on requester to send confirmation text. requestor_number = decrypted_requestor["phone"] requestor_carrier = decrypted_requestor["phone_carrier"] text_requestor = getTextRecipient(requestor_number, requestor_carrier) # Construct message to send to requestor msg_subject = "Your task has been claimed!" msg_body = decrypted_fulfiller["first_name"] + " " + decrypted_fulfiller["last_name"] + \ " has claimed your task '" + title + "'. You can get in touch with " + \ decrypted_fulfiller["first_name"] + " at " + decrypted_fulfiller["phone"] + "." # Send confirmation message to requestor if request.referrer and request.referrer != '/test': emails.send_email(msg_subject, [text_requestor], msg_body, msg_body) # Get confirmation word word = cool_word.get_cool_word() return render_template("confirmationwambam.html", cool_word = word, title = title, location = location, expiration = expiration, description = description, email = email, bid = "$%(bid).2f" % {"bid": bid}, phone = decrypted_requestor["phone"], desktop_client=request.cookies.get("mobile"))
def delegation_notify(notifications, session): ctx = app.test_request_context() ctx.push() send_email('[LQFB] Delegationen', app.config['ADMINS'][0], ['*****@*****.**'], render_template('delegations_email.txt', notifications=notifications), render_template('delegations_email.html', notifications=notifications))