mailtb.cfg: Added to repository, for the sake of a simple module configuration.
authorPascal Volk <user@localhost.localdomain.org>
Sat, 14 Nov 2009 10:09:26 +0000
changeset 3 7062c52d3999
parent 2 731c43b63c9d
child 4 bc4d326e5a46
mailtb.cfg: Added to repository, for the sake of a simple module configuration. mailtb.py: Added load_config() in order to load a mailtb.cfg file. Renamed mail_config to config
mailtb.cfg
mailtb.py
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mailtb.cfg	Sat Nov 14 10:09:26 2009 +0000
@@ -0,0 +1,59 @@
+# configuration file for the mailtb module (mailtb.py)
+#
+#	/!\ WARNING /!\
+# either:
+#     Place this file outside of your web server's document root!
+# or:
+#     Make sure that your web server does not serve this file!
+
+[mailtb]
+; subject of the email
+subject = Exception Notification
+#
+# Sender information
+#
+; The FROM e-mail address
+from_addr = webmaster@example.com
+; Sender's full name
+from_name = Webmaster
+
+#
+# Recipient information
+#
+; E-Mail address of the recipient
+rcpt_addr = john.doe@example.net
+; Recipient's full name
+rcpt_name = John Doe
+
+#
+# SMTP server information
+#
+; Hostname of the mail server for sending e-mails
+smtp_host = localhost
+; Port to use for the SMTP connection:
+;   *  25 smtp
+;   * 587 submission
+;   * 465 ssmtp (obsolete)
+smtp_port = 25
+; Should we use the starttls command on port 25 or 587?
+; If the starttls command fails no message will be sent!
+; The error will be written to 'error_log'
+;    * True or False
+smtp_tls =  False
+
+#
+# SMTP AUTH settings
+# leave empty if you don't need it
+#
+; Your SMTP user name for authentication
+auth_user =
+; Your password for SMTP authentication
+auth_pass =
+
+#
+# Log file for SMTP errors
+# make sure that your web server can write to this file
+#
+; Absolute path to the error log file
+error_log = /tmp/mailtb_error.log
+
--- a/mailtb.py	Sat Nov 14 06:01:06 2009 +0000
+++ b/mailtb.py	Sat Nov 14 10:09:26 2009 +0000
@@ -18,24 +18,24 @@
 from os import environ as env
 from time import ctime, gmtime, localtime, strftime, time
 
-mail_config = {# sender information
-               'from_addr': '',
-               'from_name': '',
-               # smtp auth information (if necessary, else leave blank)
-               'auth_user': '',
-               'auth_pass': '',
-               # recipient information
-               'rcpt_addr': '',
-               'rcpt_name': '',
-               # smtp server information
-               'smtp_host': 'localhost',
-               'smtp_port': 25, # 25 smtp, 587 submission, 465 ssmtp (obsolete)
-               'smtp_tls':  False, # True or False (use starttls on port 25/587)
-               # subject of the email
-               'subject': 'Exception Notification',
-               # make sure that the web server can write to this file
-               'error_log': '/tmp/mailtb_error.log'
-              }
+config = {# sender information
+          'from_addr': '',
+          'from_name': '',
+          # smtp auth information (if necessary, else leave blank)
+          'auth_user': '',
+          'auth_pass': '',
+          # recipient information
+          'rcpt_addr': '',
+          'rcpt_name': '',
+          # smtp server information
+          'smtp_host': 'localhost',
+          'smtp_port': 25, # 25 smtp, 587 submission, 465 ssmtp (obsolete)
+          'smtp_tls':  False, # True or False (use starttls on port 25/587)
+          # subject of the email
+          'subject': 'Exception Notification',
+          # make sure that the web server can write to this file
+          'error_log': '/tmp/mailtb_error.log'
+         }
 
 http_status = {200: 'OK',
                500: 'Internal Server Error'}
@@ -44,12 +44,25 @@
     try:
         prefix = strftime('%b %d %H:%M:%S', localtime(timestamp))
         line = error.message if len(error.message) else error.args
-        logfile = open(mail_config['error_log'], 'a')
+        logfile = open(config['error_log'], 'a')
         logfile.write('%s %s: %s\n' % (prefix, error.__class__.__name__, line))
         logfile.close()
     except:
         pass
 
+def load_config(filename):
+    from ConfigParser import ConfigParser
+    cp = ConfigParser()
+    if len(cp.read(filename)):
+        global config
+        get = cp.get
+        for k in ('auth_pass', 'auth_user', 'error_log', 'from_addr',
+                'from_name', 'rcpt_addr', 'rcpt_name', 'smtp_host', 'subject'):
+            config[k] = get('mailtb', k)
+        config['smtp_port'] = cp.getint('mailtb', 'smtp_port')
+        config['smtp_tls'] = cp.getboolean('mailtb', 'smtp_tls')
+    del(cp)
+
 def send_header(status=500, xhtml=False):
     s = status if status in http_status else 500
     write = sys.stdout.write
@@ -83,11 +96,11 @@
 </html>"""
 
 def send_mail(info):
-    global mail_config
-    mail_config['now'] = time()
-    mail_config['host'] = info['host'] if info['host'] != 'n/a' else 'localhost'
-    mail_config['date'] = strftime('%a, %d %b %Y %H:%M:%S +0000',
-            gmtime(mail_config['now']))
+    global config
+    config['now'] = time()
+    config['host'] = info['host'] if info['host'] != 'n/a' else 'localhost'
+    config['date'] = strftime('%a, %d %b %Y %H:%M:%S +0000',
+            gmtime(config['now']))
     body = """Hi,
 
 an uncaught exception has occurred. The details are as follows:
@@ -114,24 +127,22 @@
 MIME-Version: 1.0
 Content-Type: text/plain; charset=utf-8
 Content-Transfer-Encoding: 8bit
-""" % mail_config
+""" % config
     
     try:
-        if mail_config['smtp_port'] != 465:
-            smtp = smtplib.SMTP(mail_config['smtp_host'],
-                    mail_config['smtp_port'])
-            if mail_config['smtp_tls']:
+        if config['smtp_port'] != 465:
+            smtp = smtplib.SMTP(config['smtp_host'], config['smtp_port'])
+            if config['smtp_tls']:
                 smtp.starttls()
         else:
-            smtp = smtplib.SMTP_SSL(mail_config['smtp_host'],
-                    mail_config['smtp_port'])
-        if len(mail_config['auth_user']) and len(mail_config['auth_pass']):
-            smtp.login(mail_config['auth_user'], mail_config['auth_pass'])
-        smtp.sendmail(mail_config['from_addr'], mail_config['rcpt_addr'],
+            smtp = smtplib.SMTP_SSL(config['smtp_host'], config['smtp_port'])
+        if len(config['auth_user']) and len(config['auth_pass']):
+            smtp.login(config['auth_user'], config['auth_pass'])
+        smtp.sendmail(config['from_addr'], config['rcpt_addr'],
                 '\n'.join((header, body)))
     except Exception, e:
         # try to log it (fire and forget)
-        log_mail_error(e, mail_config['now'])
+        log_mail_error(e, config['now'])
     finally:
         smtp.quit()
 
@@ -155,5 +166,7 @@
     send_mail(info)
     send_error_page()
 
-def enable():
+def enable(filename=None):
+    if filename is not None:
+        load_config(filename)
     sys.excepthook = mailtbhook