Skip to content

Commit

Permalink
More enhancements
Browse files Browse the repository at this point in the history
  • Loading branch information
takwas committed Jun 18, 2016
1 parent 8a92833 commit e966794
Show file tree
Hide file tree
Showing 8 changed files with 704 additions and 204 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ temp.py
*~
*.swp
*.pyc
*.log
*.orig
.hg
*hgignore*
Expand Down
87 changes: 0 additions & 87 deletions app_log.log

This file was deleted.

190 changes: 84 additions & 106 deletions contact_form/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,25 +42,97 @@
else:
logger.setLevel(logging.INFO)
file_handler = logging.FileHandler('app_log.log')
formatter = logging.Formatter('%(asctime)s | %(levelname)s: %(message)s', datefmt='%a %b, %Y (%I:%M:%S %p)')
formatter = logging.Formatter('%(asctime)s | %(levelname)s:\t%(message)s', datefmt='%a %b, %Y (%I:%M:%S %p)')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)


def log_newline(num_lines=1):
for i in range(num_lines):
logger.info('\n')


def log_break():
logger.info('\n\n---\n\n')


def is_valid_url(url):
import requests as r
page = r.get(url)
if page.status_code == 200:
page.content

return False


def validate_email(email):
if validator(email):
return True
else:
raise EmailValidationError


def send_email(app, recp, message, sender=None, subject="Someone sent a message from your website."):

# if recipient is passed as a string,
# remove whitespaces and commas, splitting
# the string into a list of recipients
if isinstance(recp, str) or isinstance(recp, unicode):
recp = [k.strip() for k in recp.split(',')]

if sender is None:
sender=config.MAIL_SENDER
try:
mail_msg = Message(
subject=subject,
recipients=recp,
html=message,
sender=sender
)

mail.send(mail_msg)
return True
except Exception, e:
#print 'Error formatting and sending email!' # DEBUG
logger.error('Error formatting and sending email!', exc_info=True)
return False


def format_msg_html(**kwargs):
param_dict = dict()

param_dict['name'] = kwargs.get('name', 'None').title()
param_dict['email'] = kwargs.get('email', 'None')
param_dict['phone'] = kwargs.get('phone', 'None')
subject = kwargs.get('subject', 'No subject')
message = kwargs.get('message', 'No message')

return render_template(
'email_html.html',
param_dict=param_dict,
subject=subject,
message=message
)


class EmailValidationError(Exception):
pass


@app.route('/index/', methods=['GET', 'POST'])
@app.route('/', methods=['GET', 'POST'])
def index():

if request.method == 'POST':
logger.info('\n')
log_newline(2)
logger.info('New contact-us form received!')
logger.info('Site: %s', str(request.referrer))
form_dict = dict(request.form)
logger.info('Form: %s', str(form_dict))

data_fields = ['name', 'phone', 'email', 'subject', 'message']
data = dict()

try:
for k,v in form_dict.iteritems():
if k in data_fields and bool(v[0]):
Expand All @@ -80,9 +152,9 @@ def index():
#message = '{subj}\n\n{msg}'.format(subj=data.get('subject', ''), msg=data.get('message', '')).strip()
message = format_msg_html(**data)
if site is not None:
recp = site.email
logger.info('Site found in records!')
if send_email(app, recp=recp, message=message, sender=config.MAIL_SENDER, subject="Contact-Form: New message from your website."):
recp = site.email
if send_email(app, recp=recp, message=message, sender=config.MAIL_SENDER, subject="ContactForm: New message from your website."):
logger.info('Email sent to %s', str(data.get('email')))
return render_template('success.html',
goto=request.referrer,
Expand All @@ -91,81 +163,24 @@ def index():
else:
logger.error('Site not found in records!')

logger.error('Email not sent!\n\t%s\n\n---\n\n\n', str(request.form))
logger.error('Email not sent!\n\t%s', str(request.form))
log_break()
#print 'Error! Not sending mail...\n\t%r' % request.form # DEBUG
return render_template('failure.html',
goto=request.referrer,
message="There was an error. Your message was not sent. Please try again."
)

logger.info('Home page hit, redirecting to signup...')
log_newline()
return redirect(url_for('signup'))


def format_msg_html(**kwargs):
result = ''

name = kwargs.get('name')
if name is not None:
result += '**Name**: {}\n'.format(name)

email = kwargs.get('email')
if email is not None:
result += '**Email**: {}\n'.format(email)

phone = kwargs.get('phone')
if phone is not None:
result += '**Phone**: {}\n\n'.format(phone)

subject = kwargs.get('subject')
if subject is not None:
result += '**Subject**: {}\n'.format(subject)

message = kwargs.get('message')
if message is not None:
result += '**Message**: {}\n'.format(message)

return result

# @app.route('/send_mail/', methods=['POST'])
# def submit_message():
# form_dict = dict(request.form)

# data_fields = ['name', 'phone', 'email', 'message']
# data = dict()

# try:
# for k,v in form_dict.iteritems():
# if k in data_fields and bool(v[0]):
# data[k] = unicode(v[0]).decode('utf-8')
# except:
# print 'Failed to handle form:\n\t%r' % request.form # DEBUG
# return render_template('failure.html',
# goto=request.referrer,
# message="There was an error. Your message was not sent. Please try again."
# )

# if data.get('email'):
# print '\nREFERRER %s\n' % request.referrer # DEBUG
# site = db_ops.ret_val(db_ops.Site, dict(url=request.referrer))
# if site is not None:
# if send_email(app, data.get('email'), message=data.get('message'), sender=config.MAIL_SENDER, subject="Contact-Form: New message from your website."):
# return render_template('success.html',
# goto=request.referrer,
# message="Your message was sent successfully."
# )

# print 'Error! Not sending mail...\n\t%r' % request.form # DEBUG
# return render_template('failure.html',
# goto=request.referrer,
# message="There was an error. Your message was not sent. Please try again."
# )


@app.route('/signup/', methods=['GET', 'POST'])
def signup():

if request.method == 'POST':
logger.info('\n')
log_newline(2)
logger.info('New signup form received!')
form_dict = dict(request.form)
logger.info('Form: %s', str(form_dict))
Expand All @@ -176,7 +191,7 @@ def signup():
param_dict['url'] = form_dict.get('url')[0]
param_dict['email'] = form_dict.get('email')[0]
param_dict['password'] = form_dict.get('password')[0]

#verifyurl
# Need to cleanup this code
if validate_email(param_dict.get('email', 'invalid_email')):
if db_ops.insert_val(db_ops.Site, param_dict, rollback_on_fail=True):
Expand All @@ -193,7 +208,7 @@ def signup():
message="There was an error. Your registration was unsuccessful. Please try again."
)
finally:
logger.info('\n\n---\n\n')
log_break()
param_dict.clear()

return render_template('signup.html')
Expand All @@ -209,42 +224,5 @@ def _404(error):
return redirect(request.referrer), 404


def validate_email(email):
if validator(email):
return True
else:
raise EmailValidationError


def send_email(app, recp, message, sender=None, subject="Someone sent a message from your website."):

# if recipient is passed as a string,
# remove whitespaces and commas, splitting
# the string into a list of recipients
if isinstance(recp, str) or isinstance(recp, unicode):
recp = [k.strip() for k in recp.split(',')]

if sender is None:
sender=config.MAIL_SENDER
try:
mail_msg = Message(
subject=subject,
recipients=recp,
html=message,
sender=sender
)

mail.send(mail_msg)
return True
except Exception, e:
#print 'Error formatting and sending email!' # DEBUG
logger.error('Error formatting and sending email!', exc_info=True)
return False


class EmailValidationError(Exception):
pass


if __name__ == '__main__':
app.run()
16 changes: 10 additions & 6 deletions contact_form/config.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
import os
SQLALCHEMY_COMMIT_ON_TEARDOWN = True

# database config
BASE_URI = os.path.dirname(__file__)
DB_URI = os.path.join(BASE_URI, '.contact_form_data.sqlite')
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + DB_URI
SQLALCHEMY_TRACK_MODIFICATIONS = True
MAIL_SENDER = os.environ.get('CONTACT_FORM_EMAIL') #'[email protected]'

# mail protocol config
MAIL_SENDER = os.environ.get('CONTACT_FORM_EMAIL', '[email protected]')
MAIL_SERVER = 'smtp.mail.yahoo.com'
MAIL_PORT = 587
MAIL_USE_TLS = True
MAIL_USE_SSL = False

# gmail authentication
MAIL_USERNAME = os.environ.get('CONTACT_FORM_MAIL_USERNAME')
MAIL_PASSWORD = os.environ.get('CONTACT_FORM_MAIL_PASSWORD')
# mail service authentication
MAIL_USERNAME = os.environ.get('CONTACT_FORM_MAIL_USERNAME', MAIL_SENDER)
MAIL_PASSWORD = os.environ.get('CONTACT_FORM_MAIL_PASSWORD', '')

DEBUG = True
#DEBUG = True
Loading

0 comments on commit e966794

Please sign in to comment.