CGI email script

Kent Johnson kent3737 at
Sun Nov 21 03:23:08 CET 2004

bojanraic at wrote:
> I'm trying to write a basic Python email CGI script to send email
> through HTML email form.
> I've seen a lot of examples out there, but nothing I tried so far
> seemed to work. So I would like to know what I am doing wrong.
> #!/usr/bin/python
> import cgitb
> cgitb.enable()
> import cgi
> import smtplib
> print "Content-type: text/html\n"

This line should be inside main() so it is printed each time the script 
runs (OK maybe for a CGI it doesn't matter...), and it should have two 
\n - you need a blank line between the HTTP headers and the body.

> def main():
>     form = cgi.FieldStorage()
>     if form.has_key("name") and form["name"].value != "":
>         fromaddress = form["email"].value
>         toaddress = my at
>         message = form["comment"].value
>     server = smtplib.SMTP('localhost')
>     server.set_debuglevel(1)
>     server.sendmail(fromaddress, toaddress, message)

Strangely enough, the message actually has to include the from and to 
addresses as well. Try something like this:
     msg = '''From: %s
To: %s
Subject: Test
''' % (fromaddress, toaddress, message)

     server.sendmail(fromaddress, toaddress, message)

>     server.quit()
>     print "<html><head><title>Sent</title></head>"
>     print "<body><h1 align=center>",
>     print "<p>Your message has been sent!</body>"
>     print "</html>"
> if __name__ == '__main__': main()
> Of course, I change the email address to my own.
> I keep getting the premature end of script headers error.
> Several questions:
> 1. server = smtplib.SMTP('localhost') should return the name of the
> server, right? I don't need to explicitly name it, or do I?

You should pass the name of the SMTP server, is that on your local machine?


> 2. cgitb.enable() - shouldn't that give me a trace back if something
> goes wrong so I can debug the code? It doesn't seem to give me
> anything...
> 3. What am I doing wrong here? How can I fix the errors and make it
> work?

More information about the Python-list mailing list