473,396 Members | 2,111 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

CGI email script

Hi!

I recently started playing with Python CGI, and I was happy that my
basic input-name--print-hello-name CGI form example worked, so I
thought I should advance to somew\hat more complicated scripts.

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.

Here's the HTML form file:

<html>

<head>
<title>Email Form</title>
</head>

<body>

<FORM METHOD="POST" ACTION="sendMail.cgi">
<INPUT TYPE=HIDDEN NAME="key" VALUE="process">
Your name:<BR>
<INPUT TYPE=TEXT NAME="name" size=60>
<BR>
Email:<BR>
<INPUT TYPE=TEXT NAME="email" size=60>
<BR>
<P>
Comments:<BR>
<TEXTAREA NAME="comment" ROWS=8 COLS=60>
</TEXTAREA>
<P>
<INPUT TYPE="SUBMIT" VALUE="Send">
</FORM>

</body>

</html>

Here's the CGI script:

#!/usr/bin/python

import cgitb
cgitb.enable()
import cgi
import smtplib

print "Content-type: text/html\n"

def main():
form = cgi.FieldStorage()
if form.has_key("name") and form["name"].value != "":
fromaddress = form["email"].value
toaddress = my@email.com
message = form["comment"].value

server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
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?
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?

Please understand that I have read all the previous questions on this
matter, and when I tried to follow the instructions, none of them
seemed to work for me.

Any help will be greatly appreciated.
Jul 18 '05 #1
6 5382
bo*******@gmail.com 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@email.com
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
%s
''' % (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?

Kent
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?

Jul 18 '05 #2
bo*******@gmail.com wrote:
1. server = smtplib.SMTP('localhost') should return the name of the
server, right? I don't need to explicitly name it, or do I?
It returns an SMTP object to the machine known by the name "localhost". Most
machines are configured to think of themselves as "localhost".

3. What am I doing wrong here? How can I fix the errors and make it
work?


One way to investigate the error would be to pass the form parameters
directly, rather than through cgi.FieldStorage, running the script from the
command line to see any tracebacks.

Jeffrey
Jul 18 '05 #3
Kent Johnson wrote:
Strangely enough, the message actually has to include the from and to
addresses as well.


The From: and To: headers do not need to be in the message for SMTP to work.
The mail would still be delivered normally without them, but the message
will arrive appearing at first glance to be from nobody, and to nobody. A
close look at the full Received: headers may reveal at least the intended
recipient.

Jeffrey
Jul 18 '05 #4
On Sat, 20 Nov 2004 21:23:08 -0500, Kent Johnson <ke******@yahoo.com>
declaimed the following in comp.lang.python:
bo*******@gmail.com wrote:
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.


Uhmmm... Doesn't the "print" itself emit a newline? If so, only
the single explicit newline is needed to get the double spacing.
-- ================================================== ============ <
wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.netcom.com/> <

Jul 18 '05 #5
bo*******@gmail.com wrote:
Hi!

I recently started playing with Python CGI, and I was happy that my
basic input-name--print-hello-name CGI form example worked, so I
thought I should advance to somew\hat more complicated scripts.

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.

Here's the HTML form file:

<html>

<head>
<title>Email Form</title>
</head>

<body>

<FORM METHOD="POST" ACTION="sendMail.cgi">
<INPUT TYPE=HIDDEN NAME="key" VALUE="process">
Your name:<BR>
<INPUT TYPE=TEXT NAME="name" size=60>
<BR>
Email:<BR>
<INPUT TYPE=TEXT NAME="email" size=60>
<BR>
<P>
Comments:<BR>
<TEXTAREA NAME="comment" ROWS=8 COLS=60>
</TEXTAREA>
<P>
<INPUT TYPE="SUBMIT" VALUE="Send">
</FORM>

</body>

</html>

Here's the CGI script:

#!/usr/bin/python

import cgitb
cgitb.enable()
import cgi
import smtplib

print "Content-type: text/html\n"
It's conventional, though I believe strictly unnecessary, to include a
carriage return in the terminator sequence "Content ... \r\n". Of course
your Python system will take platform specific action with the line
ending *it* inserts, of course :-)
def main():
form = cgi.FieldStorage()
if form.has_key("name") and form["name"].value != "":
fromaddress = form["email"].value
toaddress = my@email.com
Well, this is certainly an error, because "toaddress" should be a list
of addresses (allowing you to send the same message to more than one
person - usually you'd include everyone in the "From:", "Cc:" and "Bcc:"
headers). I'm presuming you just forgot the quotes when you erased your
own email address. What you probably want here is

toaddress = ["my@email.invalid"]

or whatever. The "invalid" top-level domain is always the best one to
use when you want to be sure you aren't using a real address.
message = form["comment"].value
here you really do need to be including some SMTP headers in your mail,
though a lot of mailers will be quite forgiving about this. I'd probably
use something like

message = """\
From: %s
To: %s
Subject: A message from your web site

%s
""" % (fromaddress, toaadress[0], form["comment"].value
server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
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?
Most systems will resolve localhosts to 127.0.0.1, so as long as your
web server runs an SMTp server as well this will work.
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...
cgitb.enable() does try to produce output, but in this case you will
probably only be able to see it in your server's error log. That's a
sign that the error's occurring very early on int he sequence, which is
puzzling. Of course, if your web server's Python is old enough not to
*implement* cgitb then this would account for the error you are actually
seeing.
3. What am I doing wrong here? How can I fix the errors and make it
work?
Well, there are a few things to try here.
Please understand that I have read all the previous questions on this
matter, and when I tried to follow the instructions, none of them
seemed to work for me.

Any help will be greatly appreciated.


done-my-best-ly y'rs - steve
--
http://www.holdenweb.com
http://pydish.holdenweb.com
Holden Web LLC +1 800 494 3119
Jul 18 '05 #6
> server.set_debuglevel(1)

Note that this line will cause debug messages to be printed before the
start of your HTML.

I've done a set of three functions for sending mail from CGI - one of
them should work ! I usually end up using the sendmailme function,
which isn't cross platform.

import os
import sys

SENDMAIL = "/usr/sbin/sendmail" # location of sendmail on
the server

################################################## ###########
# Three alternative methods of sending email
# Which one works will depend on your server setup.

def mailme(to_email, email_subject, msg, from_email=None,
host='localhost'):
"""A straight email function using smtplib.
With localhost set as host, this will work on many servers.
"""
head = "To: %s\r\n" % to_email
if from_email:
head = head + ('From: %s\r\n' % from_email)
head = head + ("Subject: %s\r\n\r\n" % email_subject)
msg = head + msg
import smtplib
server = smtplib.SMTP(host)
server.sendmail(from_email, [to_email], msg)
server.quit()
def sendmailme(to_email, email_subject, msg, from_email=None,
sendmail=SENDMAIL ):
"""Quick and dirty, pipe a message to sendmail.
Can only work on UNIX type systems with sendmail.
Will need the path to sendmail - can be specified in the
'SENDMAIL' default (see top of this script).
"""
o = os.popen("%s -t" % sendmail,"w")
o.write("To: %s\r\n" % to_email)
if from_email:
o.write("From: %s\r\n" % from_email)
o.write("Subject: %s\r\n" % email_subject)
o.write("\r\n")
o.write("%s\r\n" % msg)
o.close()

def loginmailme(to_email, email_subject, msg, host, user, password,
from_email=None ):
"""Email function for an smtp server you need to login to.
Needs hostname, username, password etc.
"""
head = "To: %s\r\n" % to_email
if from_email:
head = head + ('From: %s\r\n' % from_email)
head = head + ("Subject: %s\r\n\r\n" % email_subject)
msg = head + msg

import smtplib
server = smtplib.SMTP(host)
server.login(user, password)
server.sendmail(from_email, [to_email], msg)
server.quit()
Jul 18 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: krystoffff | last post by:
Hi all ! I've got a very weird problem ! I was trying to make my PHP script to send emails to every subscribed member to go faster (each email takes 1 or 2 seconds to be sent !) so I tried to...
12
by: Chuck Anderson | last post by:
Can anyone point me in the right direction? I want to use Php to automate confirmation of someone joining an email list by them replying to an email (so they don't have to have a browser?). I...
9
by: mcp6453 | last post by:
I'm posting in desperation and hopes that someone has a script that will achieve these objectives: 1. Web interface using forms collects Name, Address, Email Address. 2. Web interface sends this...
4
by: Bill | last post by:
Is it possible to somehow activate a page containing a php script by sending an email to a mailbox on the server? I have a script that sends out notification emails to an individual. He wants to...
0
by: John Silver | last post by:
I have a perl script running on machine A, a web server. A visitor completes certain pieces of data and these are compiled into two emails, one addressed to the visitor and copied to the site...
4
by: web_design | last post by:
I put this together from some other scripts I am using on a site. I'm trying to make a better email hiding script. It isn't working. Also, it causes Internet Explorer 6 SP2 to block the script...
2
by: E.T. Grey | last post by:
Is it possible to have a PHP script receive an email (CSV text). The problem is this, I want a server to send me an email, and then I want to be able to have a PHP script 'listening' for email and...
4
by: ianbarton | last post by:
Hello all I am trying to setup a feedback form on my webpage using some script provided by my ISP. I really don't know a lot about PHP and it's syntax etc. The feedback form only has 4...
9
by: Jerim79 | last post by:
I am no PHP programmer. At my current job I made it known that I was no PHP programmer during the interview. Still they have given me a script to write with the understanding that it will take me a...
6
by: cfish | last post by:
I'm trying to script my contact page and I have everything the way I want it however I cannot get my script to output Address, City, State, Zip & Phone Number when I get a email. It will output...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.