def unsubscribe(): """ IF JUST LOADING THE PAGE """ if request.method == "GET": return render_template('unsub.html') """ OTHERWISE RESPONDING TO UNSUBSCRIBE POST REQUEST """ if request.method == "POST": # return render_template('unsub.html', disabled=True) # uncomment for disable details = request.form email = details['email'] # LOGIN TO DB db = credentials.dbconnect() cursor = db.cursor() sql2 = """SELECT * FROM emails""" cursor.execute(sql2) results = [i[0] for i in cursor.fetchall()] # BLANK ENTRY serverside validate if len(email) == 0: return render_template('unsub.html', subscribed='False') # FALSE UNSUBSCRIBE serverside check elif email not in results: db.commit() db.close() return render_template('unsub.html', subscribed='False') # If all serverside checking has PASSED else: # REDIRECT to the confirm unsubscribe page, with given email return redirect( url_for('confirm_unsubscribe', email=details['email']))
def confirm_unsubscribe(): email = request.args['email'] db = credentials.dbconnect() cursor = db.cursor() sql = """SELECT * FROM emails WHERE emails='{}' """.format(email) cursor.execute(sql) unsubscribe_code = cursor.fetchall()[0][2] """ IF THE PAGE IS LOADED WITH INITITALLY, SEND AN EMAIL TO """ if request.method == 'GET': newsletter.send_code(email, unsubscribe_code) return render_template('confirm_unsubscribe.html', email=email) """ CODE CHECK - POST REQUEST """ if request.method == 'POST': details = request.form # If it matches the code -- DELETE QUERY if details['unsubscribe_code'] == unsubscribe_code: sql = """DELETE FROM emails WHERE emails='{}' """.format(email) cursor.execute(sql) db.commit() db.close() # FAREWELL page render return render_template('farewell.html') # Otherwise, re-request else: return render_template('confirm_unsubscribe.html', wrong='False')
def admin(): """If SUBMITTING username and password """ if request.method == 'POST': # Get database db = credentials.dbconnect() cursor = db.cursor() sql = """SELECT * FROM admin""" cursor.execute(sql) results = [i[1:] for i in cursor.fetchall()] # Get submitted details submittedCredentials = ( request.form['username'], hashlib.sha256(request.form['password'].encode()).hexdigest()) # Password handling if submittedCredentials in results: session['username'] = request.form['username'] return redirect(url_for('adminpanel')) else: return render_template('adminpanel--login.html', credentialsWrong=True) """IF first loading the page""" if request.method == 'GET': if 'username' in session: return redirect(url_for('adminpanel')) else: return render_template('adminpanel--login.html')
def changepassword(): try: if session['username']: # HANDLING POST DATA if request.method == 'POST': db = credentials.dbconnect() cursor = db.cursor() sql = """SELECT password FROM admin WHERE username='******'""".format( session['username']) cursor.execute(sql) oldPassword = cursor.fetchall()[0][0] # most important, check for the oldpasswords to match if hashlib.sha256(request.form['oldPassword'].encode() ).hexdigest() == oldPassword: # check for newpasswords to match, otherwise return back if request.form['newPassword'] != request.form[ 'newPassword2']: return redirect( url_for('changepassword', passwordsNotMatch=True)) else: # delete the password that preexists sql_deletepassword = """DELETE FROM admin WHERE username='******';""".format( username=session['username']) cursor.execute(sql_deletepassword) # add in the new password sql_changepassword = """INSERT INTO admin (username, password) VALUES ('{username}', '{passwordHash}');""".format( username=session['username'], passwordHash=hashlib.sha256( request.form['newPassword'].encode( )).hexdigest()) print(sql_deletepassword, sql_changepassword) cursor.execute(sql_changepassword) # commits the changes db.commit() db.close() return redirect( url_for('changepassword', changedPassword=True)) # if old password match fails, return back else: return redirect( url_for('changepassword', incorrectPassword=True)) # IF RESPONDING TO PAGE LOAD if request.method == "GET": return render_template('adminpanel--changepassword.html', username=session['username']) except Exception as e: return 'unauthorised'
def view_subscribed(): try: if session['username']: db = credentials.dbconnect() cursor = db.cursor() sql = """SELECT * FROM emails""" cursor.execute(sql) emailList = [i[0] for i in cursor.fetchall()] emailList.sort() return render_template('adminpanel--view_subscribed.html', emailList=emailList) except Exception as e: return 'unauthorised'
def send_newsletter_to(EMAIL): """ Sends a welcome newsletter, with instructions, to the email in the parameter """ import emailformatter # builds email html import credentials # takes credentials MY_ADDRESS = credentials.username # email address MY_PASSWORD = credentials.password # insert password on run, delete after HTML_MESSAGE = emailformatter.html_message # main HTML message -- string type # Sign in s = smtplib.SMTP(host='smtp.gmail.com', port=587) s.ehlo() s.starttls() s.login(MY_ADDRESS, MY_PASSWORD) print('sign in successful ... ') # Create message msg = MIMEMultipart() # Adds the personalised stuff; to, from, subject msg['From'] = 'NC Daily' msg['To'] = EMAIL msg['Subject'] = 'Welcome to NC Daily' # Attaches HTML message msg.attach(MIMEText(HTML_MESSAGE, 'html')) # Send and delete s.send_message(msg) del msg # Add statistics import MySQLdb db = credentials.dbconnect() cursor = db.cursor() sql = """SELECT `emails_sent` FROM statistics;""" cursor.execute(sql) db.commit() results = cursor.fetchall()[0][0] results += 1 sql = """UPDATE statistics SET `emails_sent`={};""".format(results) cursor.execute(sql) db.commit() db.close()
def add_emails(): if session['username']: details = request.form emails = details['emails'].split(',') print(emails) # Connect to database and fetch all db = credentials.dbconnect() cursor = db.cursor() sql2 = """SELECT * FROM emails""" cursor.execute(sql2) results = [i[0] for i in cursor.fetchall()] for email in emails: # Boolean for Valid Email # BLANK ENTRY serverside validate if len(email) == 0: return redirect(url_for('view_subscribed', empty=True)) # SUBSCRIBING TWICE serverside validate if email in results: db.close() return redirect( url_for('view_subscribed', email=email, duplicate=True)) # All serverside validation PASSED successfully else: # Add email to database sql = """INSERT INTO emails(emails, subscription_status, unsubscribe_code) VALUES ('{}', 1, '{:05}' )""".format( email.strip(), random.randint(0, 10000)) cursor.execute(sql) db.commit() # Send them welcome message # newsletter.send_newsletter_to(email) # Renders the welcome page -- DOES NOT REDIRECT db.close() return redirect(url_for('view_subscribed', successfullyAdded=True)) else: return 'unauthorised'
def delete_emails(): if session['username']: try: emailScrap = request.form['emailScrap'].split(',') db = credentials.dbconnect() cursor = db.cursor() for email in emailScrap: sql = """DELETE FROM emails WHERE emails='{}'""".format(email) cursor.execute(sql) db.commit() db.close() return redirect( url_for('view_subscribed', numberDeleted=len(emailScrap), errorDelete=False)) except Exception as e: return redirect(url_for('view_subscribed', errorDelete=True)) else: return 'unauthorised'
def main(emails_sent): # Define emails to clean bad_emails = [] # Define statistical variables start_time = time.time() # SIGN IN s = smtplib.SMTP(host='smtp.gmail.com', port=587) # s.set_debuglevel(1) s.ehlo() s.starttls() s.login(MY_ADDRESS, MY_PASSWORD) print('sign in successful ... ') # ITERATES OVER ALL EMAILS for address, subscription_status in results: # Throttle app at 50, 100, 150 ... if emails_sent % 30 == 0 and emails_sent != 0: print('emails_sent:', emails_sent, '... throttling app for 60s') time.sleep(50) print('\t...attempting to login into smtp again') s.connect(host='smtp.gmail.com', port=587) s.ehlo() s.starttls() s.login(MY_ADDRESS, MY_PASSWORD) print('sign in successful ... ') if subscription_status == 0: print('\tskipping', address) continue # Create message msg = MIMEMultipart() # Adds the personalised stuff; to, from, subject msg['From'] = 'NC Daily' msg['To'] = address msg['Subject'] = '{}'.format(dateformatter.dateformatted) # Uncomment for last name in the subject - address.split('@')[0][:-1].title()) # Attaches HTML message msg.attach(MIMEText(html_message, 'html')) # Send, error check and then delete - to prevent memory overflow try: s.send_message(msg) emails_sent += 1 print('\temailed ' + address) except Exception as e: print(address, 'got', e, '...adding to bad emails') bad_emails.append(address) # Delete del msg # Add statistics of looptime/emails_sent to the json file and reconnect db = credentials.dbconnect() print('uptime:',time.time() - start_time) sql = """UPDATE statistics SET `loop_time`={looptime}, `uptime`={uptime}, `emails_sent`={emails_sent};""".format(looptime=time.time() - start_time ,uptime=uptime, emails_sent=emails_sent) cursor = db.cursor() cursor.execute(sql) db.commit() # Clean out bad emails for address in bad_emails: try: s = smtplib.SMTP(host='smtp.gmail.com', port=587) s.connect(host='smtp.gmail.com', port=587) s.ehlo() s.starttls() s.login(MY_ADDRESS, MY_PASSWORD) print('sign in successful ... ') # Create message msg = MIMEMultipart() # Adds the personalised stuff; to, from, subject msg['From'] = 'NC Daily' msg['To'] = address msg['Subject'] = '{}'.format(dateformatter.dateformatted) # Uncomment for last name in the subject - address.split('@')[0][:-1].title()) # Attaches HTML message msg.attach(MIMEText(html_message, 'html')) s.send_message(msg) emails_sent += 1 print('\temailed ' + address) except Exception as e: print('\tdisabling', address, '... got ', e) sql = """UPDATE emails SET subscription_status=0 WHERE emails='{}'""".format(address) cursor.execute(sql) db.commit() db.close()
import MySQLdb import smtplib, sys from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import datetime import time import os import admintools import json import credentials """ DATABASE CONNECTION connect parameters: host, user, password, table """ db = credentials.dbconnect() cursor = db.cursor() sql = """SELECT * FROM statistics""" cursor.execute(sql) db.commit() results = cursor.fetchall() # Define statistical variables looptime = results[0][0] uptime = results[0][1] emails_sent = results[0][2] # New day uptime += 1
def adminpanel(): # IF LOGGED IN try: if session['username']: db = credentials.dbconnect() cursor = db.cursor() sql = """SELECT * FROM emails""" cursor.execute(sql) results = [i[0] for i in cursor.fetchall()] total_subs = len(results) db.commit() sql = """SELECT * FROM statistics""" cursor.execute(sql) db.commit() results = cursor.fetchall() # Define statistical variables loop_time = str(round(results[0][0], 2)) + 's' uptime_days = str(results[0][1]) + ' days' emails_sent = str(results[0][2]) + ' emails' import time try: os.environ["TZ"] = "Pacific/Auckland" time.tzset() except Exception as e: pass print(admintools.is_schooltime() and (not admintools.is_weekend()) and admintools.is_ON_declaredbyuser()) if admintools.is_schooltime() and (not admintools.is_weekend( )) and admintools.is_ON_declaredbyuser(): return render_template( 'adminpanel--home.html', appON='True', username=session['username'], totalSubscribers=total_subs, emails_sent=emails_sent, loop_time=loop_time, uptime_days=uptime_days, holiday_startdate=admintools.holiday_startdate(), holiday_enddate=admintools.holiday_enddate(), **request.args) else: return render_template( 'adminpanel--home.html', appON='False', username=session['username'], totalSubscribers=total_subs, emails_sent=emails_sent, loop_time=loop_time, uptime_days=uptime_days, holiday_startdate=admintools.holiday_startdate(), holiday_enddate=admintools.holiday_enddate(), **request.args) # ELSE TAKE BACK TO ADMIN except KeyError: return redirect(url_for('admin'))
def home(): db = credentials.dbconnect() cursor = db.cursor() sql = """SELECT `subscription_status` FROM emails""" cursor.execute(sql) results = [i[0] for i in cursor.fetchall()] num_students = ((len(results) // 10) * 10) + 10 """ IF RESPONDING TO REGULAR GET REQUEST """ if request.method == 'GET': return render_template('home.html', num_students=num_students) """ IF RESPONDING TO SUBSCRIBE POST REQUEST """ if request.method == "POST": # Define INITIAL VARIABLES details = request.form email = details['email'] #uncomment for disable #return render_template('home.html', num_students=num_students, disabled=True) # Boolean for Valid Email # is_valid = validate_email(email_address=email, \ # check_regex=True, check_mx=True, \ # smtp_timeout=2, dns_timeout=2, use_blacklist=True) # BLANK ENTRY serverside validate if len(email) == 0: return render_template('home.html', num_students=num_students, empty=True) # # INVALID EMAIL serverside validate # elif not is_valid: # return render_template('home.html', num_students=num_students,invalid_email=True) # Connect to database and fetch all db = credentials.dbconnect() cursor = db.cursor() sql2 = """SELECT * FROM emails""" cursor.execute(sql2) results = [i[0] for i in cursor.fetchall()] # SUBSCRIBING TWICE serverside validate if email in results: db.commit() db.close() return render_template('home.html', num_students=num_students, email=email, duplicate=True) if email in email_groups: return render_template('home.html', num_students=num_students, email=email, blocked=True) # All serverside validation PASSED successfully else: # Add email to database sql = """INSERT INTO emails(emails, subscription_status, unsubscribe_code) VALUES ('{}', 1, '{:05}' )""".format( email, random.randint(0, 10000)) cursor.execute(sql) db.commit() db.close() # Send them welcome message newsletter.send_newsletter_to(email) # Renders the welcome page -- DOES NOT REDIRECT return render_template('landing.html', email=email)