Difference between revisions of "CGI email"
From Noah.org
Jump to navigationJump to searchm |
m |
||
Line 216: | Line 216: | ||
else: | else: | ||
MESSAGE = form['content'].value | MESSAGE = form['content'].value | ||
− | MESSAGE = ' | + | MESSAGE = 'email from: %s\r\n\r\n%s' % (EMAIL, MESSAGE) |
if SMTP_SERVER is None: | if SMTP_SERVER is None: | ||
send_via_sendmail (TO, FROM, SUBJECT, MESSAGE) | send_via_sendmail (TO, FROM, SUBJECT, MESSAGE) |
Latest revision as of 15:34, 3 January 2013
#!/usr/bin/env python ############################################################################### # GLOBAL VARIABLES # You will need to change these to suite your purpose. # Set SMTP_SERVER to None to use 'sendmail' instead of SMTP. #SMTP_SERVER='localhost' SMTP_SERVER=None TO='Noah <noah@noah.org>' FROM='noah@noah.org' ############################################################################### """ SYNOPSIS This is a simple CGI that demonstrates sending email through a web form. This can send mail either via SMTP or via the /usr/sbin/sendmail command. DESCRIPTION Put this in your cgi-bin directory. It will create an email form web page and process the results when a user submits the form. AUTHOR Noah Spurrier <noah@noah.org> LICENSE This license is approved by the OSI and FSF as GPL-compatible. http://opensource.org/licenses/isc-license.txt Copyright (c) 2012, Noah Spurrier PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. VERSION 3 """ import sys import os import traceback import cgi import smtplib def send_via_SMTP (SMTP_SERVER, TO, FROM, SUBJECT, MESSAGE): # Add the From:, To:, and Subject: headers at the start. message = 'From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n' % (FROM, TO, SUBJECT) message = message + MESSAGE server = smtplib.SMTP(SMTP_SERVER) # server.set_debuglevel(1) server.sendmail(FROM, TO, message) server.quit() def send_via_sendmail (TO, FROM, SUBJECT, MESSAGE): from email.mime.text import MIMEText from subprocess import Popen, PIPE msg = MIMEText(MESSAGE) msg['To'] = TO msg['From'] = FROM msg['Subject'] = SUBJECT p = Popen(['/usr/sbin/sendmail', '-i', '-t'], stdin=PIPE) p.communicate(msg.as_string()) # p = os.popen(['/usr/sbin/sendmail -i -t', 'w') # p.write(msg.as_string()) # status = p.close() # if status: # print ('sendmail exit status %d' % status) DEFAULT_FORM_WEBPAGE = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Email Noah</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="ROBOTS" content="NOINDEX, NOFOLLOW"> <!-- <link rel="stylesheet" href="/css/clean.css"> --> <link rel="stylesheet" href="/w/skins/monoclean/main.css"> <script type="text/javascript"> // This will focus first non-hidden text or textarea field on the first form. function focus_first () { var form = document.forms[0]; if (form != null && form.elements[0] != null) { for (var i = 0; i < form.elements.length; ++i) { var field = form.elements[i]; if ((field.type=="text" || field.type=="textarea") && field.type!="hidden") { field.focus(); break; } } } } </script> </head> <body onload="focus_first()"> <h1>Email Noah</h1> <form method="POST"> <table width="0%" border="0"> <tr> <td>To</td> <td><img src="/email.png" width="100" height="16" alt="Noah"></td> </tr> <tr> <td>Your Name </td> <td> <input name="name" size="40"> </td> </tr> <tr> <td>Your Email</td> <td> <p> <br><input name="email" size="40"> <em>If you me to respond then don't forget your email address!</em><br> </p> </td> </tr> <tr> <td>Subject</td> <td> <input name="subject" size="80"> </td> </tr> <tr> <td valign="top"> <p>Message</p> </td> <td> <textarea name="content" rows=10 cols=80></textarea> </td> </tr> <tr> <td> </td> <td> <div align="right"> <input type="submit" value="Send" name="submit"> </div> </td> </tr> </table> </form> </body> </html> """ RESPONSE_WEBPAGE = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Email sent</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="ROBOTS" content="NOINDEX, NOFOLLOW"> <!-- <link rel="stylesheet" href="/css/clean.css"> --> <link rel="stylesheet" href="/w/skins/monoclean/main.css"> </head> <body> <h1>Email has been sent</h1> <a href="javascript:history.go(-2)"> Click to go back. </a> </p> </body> </html> """ # This redirects errors to the web browser. Normally stderr goes to the web # server errors log, but this will instead put the message on the user's web # browser. This may or may not be what you want. In a CGI, everything printed # to stdout will get sent to the web browser. So we tell Python that stderr # should get reset to stdout. This is only useful if the CGI prints an error. sys.stderr = sys.stdout # This is essential for HTTP output. The first line must always be # 'Content-type: text/html' followed by a blank line. print('Content-type: text/html') print('') try: # This is how a CGI finds out the address it needs to call itself again. # The cgi module has this attribute especially for these self-referencing # CGI scripts. form = cgi.FieldStorage() # Either process the form or print the form. if len(form) > 0: # Process the form. if 'name' not in form: NAME = 'None' else: NAME = form['name'].value if 'email' not in form: EMAIL = '<not given by user>' else: EMAIL = form['email'].value if 'subject' not in form: SUBJECT = 'test email' else: SUBJECT = form['subject'].value if 'content' not in form: MESSAGE = 'test email' else: MESSAGE = form['content'].value MESSAGE = 'email from: %s\r\n\r\n%s' % (EMAIL, MESSAGE) if SMTP_SERVER is None: send_via_sendmail (TO, FROM, SUBJECT, MESSAGE) else: send_via_SMTP (SMTP_SERVER, TO, FROM, SUBJECT, MESSAGE) print (RESPONSE_WEBPAGE) else: # This prints the HTML form if the CGI was # called without form data (length was 0). print (DEFAULT_FORM_WEBPAGE) # This only runs if there were any exceptions thrown in the try: block. # If this happens then we will print the Python program stack and error messages. # This should get sent back to the user's web browser. except: print ('\n\n<pre>') traceback.print_exc() print ('
')