Visual Basic
Web Scripting

Active Server Pages
Java


Home

Articles

Code Snippets

Links
Books

Mailing List
Receive free code snippets and notices when this site is updated.

Contact

Creating a "Tell a Friend" feature for a web site using Python

Many sites including this one have a link where you can recommend a page to a friend. I had wanted to add this function to the site for a while but my web server didn't have support for the other languages I know. Then I found out that Python was installed and decided to find out more about it. It turned out to be a good choice because of the ease that you do tasks like sending email.

For example to send a simple email all you need is the following:

import smtplib

toaddrs = "someone@somewhere.com"
fromaddr = "anyone@anywhere.com"
msg="This is the message"

server = smtplib.SMTP('mail.mymailserver.com')

server.sendmail(fromaddr, toaddrs, msg)
server.quit()

Some things to note about Python

  • Strings are placed between ' or "
    For example
    a = "This is a string"
    b = 'So is this'
  • White space matters
    Code blocks like if statements and functions are indented
    For example
    if a = b:
        print "This" # prints a new line character
    else
        print "That", # doesn't print a new line character
  • The print statement automatically prints a new line character unless there is a comma (see above).

This article won't try and cover Python's syntax so if your new to Python I recommend you download it from www.python.org and read the tutorial.

The tell a friend scripts that is used on this site uses two CGI programs written in Python.  Python is a open-source freeware (even for commercial use) object-orientated scripting language created by Guido van Rossum and named after the BBC television comedy Monty Python's Flying Circus.

tell.py

The first script (tell.py) simply takes the recommended URL and displays it on a web page along with a form to enter the name and email address of the person you are recommending the site to. To see this in action click here.

The tell.py script is shown below. Just like in Java and C strings like ' or " are escaped by using a "\".

The script checks that a value has been passed in the url attribute and displays a form if it has. Otherwise an error message is displayed, a valid URL to recommend a page would be http://www.mysitesomewhere.com/tell.py?url=http://www.developersdomain.com/

Like in many other languages 1 evaluates to true and other values to false.

#!/usr/bin/python
import cgi
print 'Content-type: text/html\r\n\r\n',
print '<html>'
form = cgi.FieldStorage()
form_ok = 0
if form.has_key("url"):
    if form["url"].value != "":
        form_ok = 1
        print '<p><b>Page url:</b> ' + form["url"].value + '</p>'
	print '<form method=post action=email.py>'
	print '<input type="hidden" name="url" value="' + form["url"].value + '"'
	print '<p>Your name: <input type="text" name="yourname" size="17"><br>'
	print 'Your email address: <input type="text" name="youremail" size="24"></p>'
	print '<p>Your friends name: <input type="text" name="theirname" size="17"><br>'
	print 'Your friend\'s email address:'
	print '<input type="text" name="theiremail" size="26"></p>'
	print '<p>Message<br>'
	print '<textarea rows="4" name="message" cols="35"></textarea></p>'
	print '<p><input type="submit" value="Submit" name="bSend">'
	print <input type="reset" value="Reset" name="B1"></p>'
	print '</form>'        
if not form_ok:
    print "<H1>Error</H1>"
    print "No page specified"
print '</body>'
print '</html>'

Sometimes you want to include some HTML with out escaping all the quotation marks such as when you want to print a large JavaScript. An easy way to do this is to place the JavaScript in another file and then open it and print it where it's needed. For example:

f=open('myjavascript.js')
print f.read();


email.py

This is the script that does most of the work.  After the user has filled out the form generated by tell.py email.py is called.

The first lines of email.py import two modules:

  • import smtplib
  • import cgi

The cgi module lets us easily get the value of a field sent using an http get or post request simply using code like form["url"].value.  

And as you have properly guessed the smtplib lets us send email using SMTP.

In email.py there are a number of statements like the following:

# Start checking for empty fields
if not form.has_key("url") or form["url"].value == "":
	print "<P>Invalid URL</P>"
	form_ok = 1

This checks to see if each of the required fields was sent and displays an error message if they weren’t

If all required fields where supplied then the next interesting bit of code creates an instance of the SMTP class.

server = smtplib.SMTP('mail.digitalchainsaw.com')

The variable msg contains the main body of the message.  We can attach other headers here, this means we can prefix the subject of the email to the start of the message.

msg = "Subject:Recommened Page\n\n" + msg

Now we are ready to send the email.  The sendmail function appears with in a try: block.  If the email can not be sent to the address a SMTPRecipientsRefused exception will be thrown and "<p>Mail could not be sent to that address</p>" will be printed.  If there is no error "<H1>Page Recommended</H1>" will be printed.

try:
      server.sendmail(fromaddr, form["theiremail"].value, msg)
except smtplib.SMTPRecipientsRefused:
	print "<p>Mail could not be sent to that address</p>"
else:
	print "<H1>Page Recommended</H1>"
server.quit()

The Complete Code

#!/usr/bin/python
import cgi
import smtplib

form = cgi.FieldStorage()
form_ok = 0

print "Content-type: text/html\r\n\r\n",
print "<HTML><HEAD><TITLE>Page Recommended</TITLE></HEAD><BODY>"

# Start checking for empty fields
if not form.has_key("url") or form["url"].value == "":
	print "<P>Invalid URL</P>"
	form_ok = 1

if not form.has_key("yourname") or form["yourname"].value == "":
	print '<p>Please enter your name</p>'
	form_ok = 1

if not form.has_key("youremail") or form["youremail"].value == "":
	print '<p>Please enter your email</p>'
	form_ok = 1

if not form.has_key("theirname") or form["theirname"].value == "":
	print '<p>Please enter your friend\'s name</p>'
	form_ok = 1

if not form.has_key("theiremail") or form["theiremail"].value == "":
	print '<p>Please enter your friend\'s email</p>'
	form_ok = 1
# End empty field check

if form_ok != 1:
	fromaddr = "webmaster@abc123zyz.com"
	url = form["url"].value
	msg = "Hi " + form["theirname"].value
	msg = msg + ",\n\nThe following url has been recommended by:\n"
	msg = msg + "Name: " + form["yourname"].value + "(" +  form["youremail"].value + ")\n"
	msg = msg + "The recommended URL is: " + url

	if form.has_key("message"):
		if form["message"].value != "":	
			msg = msg + "\n--- Message ---\n" + form["message"].value

	server = smtplib.SMTP('smtp.abc123zyz.com')

	msg = "Subject:Recommened Page\n\n" + msg
	try:
		server.sendmail(fromaddr, form["theiremail"].value, msg)
	except smtplib.SMTPRecipientsRefused:
		print 'Mail could not be sent to that address'
	else:
		print "<H1>Page Recommended</H1>"

	server.quit()
	print "<A href='" + url + "'>Click here to return to " + url + "</A>"
else:
	print "<P><B>Click the back button to fix these problems</B></P>"

print "</BODY></HTML>"

 


References

Python Language Website
The official website for the Python language

The Developer's Domain Python Book Store

Python 101
The other scripting language that starts with "P"