sendmail

Simon Brunning SBrunning at trisystems.co.uk
Wed Jun 20 16:05:43 CEST 2001


> From:	Nik Goodey [SMTP:splat_360 at flashmail.com]
> I am trying to get a form on my page email me some info.  I can;t figure 
> out how to get sendmail to get the form info and email it.
 
I'll tell you how *I've* done it. But I must warn you - I have been told
that this method is exposed to misuse. Stay tuned to c.l.py for more info on
this problem...

Anyway, my form looks like so:

<form method="post" action="mysendmail.cgi">
  <table
    <tr>
      <td align="right">Your name:</td>
      <td>
        <input type="text" name="name" size="50">
      </td>
    </tr>
    <tr>
      <td align="right">Your e-mail address:</td>
      <td>
        <input type="text" name="email" size="50">
      </td>
    </tr>
    <tr>
	  <td align="right">Subject: </td>
      <td>
        <input type="text" name="subject" size="50">
      </td>
    </tr>
    <tr>
      <td align="right" valign="top"><br>
        Your message or question:</td>
      <td>
        <textarea name="comments" cols="70" rows="6"></textarea>
      </td>
    </tr>
  </table>
  <p>
    <input type="submit" name="Submit" value="Submit">
  </p>
</form>

and the script to process it looks like this:

import sys, cgi, smtplib, traceback, StringIO

failHTML = '''Whatever HTML you want here'''
sentHTML = '''Whatever HTML you want here'''

mailtemplate = '''From: %(email)s
To: youraddress
Subject: %(subject)s
Email from %(name)s

%(comments)s'''

sent = None

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

try:
    form = cgi.FieldStorage()
    formstrings = {}
    for formfield in form.keys():
        formstrings[formfield] = form[formfield].value
    mailtext = mailtemplate % formstrings

    mailserver = smtplib.SMTP('yourSMTPserver')
    failure = mailserver.sendmail( 'youraddress', 'youraddress', mailtext)
    sent = not failure
except:
    foo = StringIO.StringIO()
    traceback.print_exc(file=foo)
    failure = foo.getvalue()

if sent:
    print sentHTML
else:
    print failHTML
    # print failure # Enable this if you are having problems...

I'm not using sendmail here - smtplib seemed easier.

BTW, any suggestions for improving this, my first CGI script, would be
warmly recieved...

Cheers,
Simon Brunning
TriSystems Ltd.
sbrunning at trisystems.co.uk




-----------------------------------------------------------------------
The information in this email is confidential and may be legally privileged.
It is intended solely for the addressee. Access to this email by anyone else
is unauthorised. If you are not the intended recipient, any disclosure,
copying, distribution, or any action taken or omitted to be taken in
reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot
accept liability for statements made which are clearly the senders own.




More information about the Python-list mailing list