Skip to content

Instantly share code, notes, and snippets.

@rfunduk
Created August 10, 2011 21:26
Show Gist options
  • Save rfunduk/1138330 to your computer and use it in GitHub Desktop.
Save rfunduk/1138330 to your computer and use it in GitHub Desktop.
<form id="comment_form"
action="/cgi-bin/comment.py"
method="post">
Full Name: <input name="full_name" /><br/>
Email <small>(optional)</small>: <input name="email" /><br/>
Subject: <select name="subject">
<option selected value="Comment">Comment</option>
<option value="Complaint">Complaint</option>
<option value="Question">Question</option>
</select><br/>
Body: <textarea name="body"></textarea><br/>
<input type="submit" value="Send" />
</form>
#!(path-to-python, eg. /usr/bin/python)
# comment.py
# A simple CGI handler for sending emails from an HTML
# form. This script supports asynchronous requests via
# Javascript as well as being requested through the normal
# browser POST behavior.
#
# Note: Make sure to set this file as executable or your web
# server will not run it! On *nix you could do this by
# running: `chmod +x comment.py`
import cgi, smtplib, datetime
data = cgi.FieldStorage( keep_blank_values = True )
error = None
if not ( len( data['full_name'].value ) and \
len( data['body'].value ) ):
error = "Your name and a message body are required."
else:
full_name = data['full_name'].value
email = data['email'].value
subject = data['subject'].value
body = data['body'].value
message_text = "\n\n".join( [ "Name: " + full_name, \
"Email: " + email, \
"Subject: " + subject, \
"Body:\n" + body ] )
if not error:
from_address = to_address = "your@email.com"
subj = "Site Contact Form"
date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" )
msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" \
% ( from_address, to_address, subj, date, message_text )
server = smtplib.SMTP( 'your.mailserver.address:25' )
server.login( 'username', 'password' )
server.sendmail( from_address, to_address, msg )
server.quit()
result = "SUCCESS!"
else:
result = "ERROR! " + error
if data.has_key( 'async' ):
print "Content-Type: text/plain\r\n\r\n"
print result
else:
print "Content-Type: text/html\r\n\r\n"
print """
<html>
<head>
<title>Form Submitted</title>
</head>
<body>
<h1>Dynamic Comment Form Submission</h1>
<p>The result of your submission is: <em>%s</em></p>
</body>
</html>""" % result
<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript">
$(document).ready( function () {
$('#comment_form').submit( function () {
$(this).fadeOut( 'fast' );
form_contents = $(this).serialize() + "&async=true";
form_action = $(this).attr( 'action' );
$.ajax( {
type: 'post',
data: form_contents,
url: form_action,
success: function( result ) {
$('#comment_form').before( "<div><tt>" +
result +
"</tt></div>" );
}
} );
return false;
} );
} );
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment