Have you ever wanted to setup a form on your website so that people can send you email? Unless you have your own server, this may be a problem depending on how your hosts email servers are setup.

I had first used a pre-written Perl script back in the day to send email through the web. However, this was before I learned to program with CGI. Some of the hosts started changing the authentication schemes for sending email. This presented a problem as most of these scripts relied on a open relay system. A open relay system allows people to send email through the server without a username and or password. Some of the free scripts stopped working as my host changed the setup of their email. Below I present a script one can use to send email from a form. The main requirement is that a person have Python 2.0 installed on their server where the website is hosted. Note due to the formatting and use of whitespace in Python, one may have to add tabs to the system. One may also have to change the location string for the python interpreter. The form that submits to this script should have the fields last_name, first_name, and email. It should also use the POST method rather than the GET method. This script is nice if you want to have a little sign up section for a mailing list on your website. You may want to spice up the output to give the user some fancy graphics, or you may want to just redirect the user to another page.

#!/usr/local/bin/python
import cgi, os, sys, string, time, smtplib

def displaydata(data):
print “%(first_name)s %(last_name)s on %(time)s email %(email)s” % vars(data)

def gush(data):
print ”

Correct, %(name)s!

” % vars(data)

def whimper(data):
print ”

Wrong, %(name)s!

” % vars(data)
def bail():
print ”

Error filling out form!


sys.exit()

def mysend(data):
fromaddr = data.email
toaddr = ” someone@somewhere.com
msg = “Mailing list application from ” + data.first_name + ” ” + data.last_name + ” “+data.email
server = smtplib.SMTP(’mail.someserver.com’)
msg = “Subject:MailingList\n\n” + msg
try:
server.sendmail(fromaddr,toaddr,msg)
except smtplib.SMTPRecipientsRefused:
print ‘Mail could not be sent to that address’
else:
print “

Mail Sent


server.quit()

class FormData:
“”" A repository for information gleaned from a CGI from “”"
def __init__(self, form):
for fieldname in self.fieldnames:
if not form.has_key(fieldname) or form[fieldname].value == “”:
bail()
else:
setattr(self, fieldname, form[fieldname].value)

class FeedbackData(FormData):
“”" A FormData generated by the mail_list.htm form “”"
fieldnames = (’last_name’, ‘first_name’, ‘email’)
def __repr__(self):
return “%(first_name)s %(last_name)s on %(time)s email %(email)s” % vars(self)

if __name__ == ‘__main__’:
sys.stderr = sys.stdout
print “Content-type: text/html\n”
print “Aaron Baker Mailing LIST
form = cgi.FieldStorage()
data = FeedbackData(form)
data.time = time.asctime(time.localtime(time.time()))
mysend(data)
print ““