mailtb.py
changeset 0 3acd8a788a6f
child 1 bab77be235a8
equal deleted inserted replaced
-1:000000000000 0:3acd8a788a6f
       
     1 #!/usr/bin/env python
       
     2 # -*- coding: UTF-8  -*-
       
     3 
       
     4 """
       
     5 Sends information about uncaught exceptions per email.
       
     6 
       
     7 """
       
     8 
       
     9 import sys
       
    10 import smtplib
       
    11 import traceback
       
    12 from os import environ as env
       
    13 from time import ctime, gmtime, localtime, strftime, time
       
    14 
       
    15 # make sure that the web server can write to this file
       
    16 mail_error_file = '/tmp/mailtb_error.log'
       
    17 mail_config = {# sender information
       
    18                'from_addr': '',
       
    19                'from_name': '',
       
    20                # smtp auth information (if necessary, else leave blank)
       
    21                'auth_user': '',
       
    22                'auth_pass': '',
       
    23                # recipient information
       
    24                'rcpt_addr': '',
       
    25                'rcpt_name': '',
       
    26                # smtp server information
       
    27                'smtp_host': 'localhost',
       
    28                'smtp_port': 25, # 25 smtp, 587 submission, 465 ssmtp (obsolete)
       
    29                'smtp_tls':  False, # True or False (use starttls on port 25/587)
       
    30                # subject of the email
       
    31                'subject': 'Exception Notification'
       
    32               }
       
    33 
       
    34 def log_mail_error(error, timestamp):
       
    35     try:
       
    36         prefix = strftime('%b %d %H:%M:%S', localtime(timestamp))
       
    37         line = error.message if len(error.message) else error.args
       
    38         logfile = open(mail_error_file, 'a')
       
    39         logfile.write('%s %s: %s\n' % (prefix, error.__class__.__name__, line))
       
    40         logfile.close()
       
    41     except:
       
    42         pass
       
    43 
       
    44 def send_header():
       
    45     write = sys.stdout.write
       
    46     #write('Content-Type: text/html; charset=utf-8\r\n')
       
    47     write('Content-Type: application/xhtml+xml; charset=utf-8\r\n')
       
    48     write('Status: 500 Internal Server Error\r\n\r\n')
       
    49     sys.stdout.flush()
       
    50 
       
    51 def send_error_page():
       
    52     send_header()
       
    53     print """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
       
    54   "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
       
    55 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de">
       
    56   <head>
       
    57     <title>Internal Server Error</title>
       
    58     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
       
    59   </head>
       
    60   <body>
       
    61     <h1>Internal Server Error</h1>
       
    62     <p>So wie es aussieht, ging bei der Bearbeitung Ihrer Anfrage etwas
       
    63     schief.</p>
       
    64     <p>Sofern Sie den Fehler verursacht haben, dürfen Sie jetzt ein schlechtes
       
    65     Gewissen haben.<br />
       
    66     Die Administration wird sich bei nächster Gelegenheit um das Problem
       
    67     kümmern. Bitte haben Sie dafür etwas Verständnis.</p>
       
    68     <h2>Error 500</h2>
       
    69     <p>Sorry</p>
       
    70   </body>
       
    71 </html>"""
       
    72 
       
    73 def send_mail(info):
       
    74     global mail_config
       
    75     mail_config['now'] = time()
       
    76     mail_config['host'] = info['host'] if info['host'] != 'n/a' else 'localhost'
       
    77     mail_config['date'] = strftime('%a, %d %b %Y %H:%M:%S +0000',
       
    78             gmtime(mail_config['now']))
       
    79     body = """Hi,
       
    80 
       
    81 an uncaught exception has occurred. The details are as follows:
       
    82 
       
    83   Type:    %(extype)s
       
    84   Message: %(message)s
       
    85 
       
    86 Traceback (most recent call last):
       
    87 %(traceback)s
       
    88 
       
    89 Additional information:
       
    90   Date:     %(date)s
       
    91   Request:  %(method)s %(uri)s %(protocol)s
       
    92   Referrer: %(referer)s
       
    93   Client:   %(addr)s/%(port)s
       
    94   U-Agent:  %(agent)s
       
    95 """ % info
       
    96     header = """Date: %(date)s
       
    97 From: "%(from_name)s" <%(from_addr)s>
       
    98 To: "%(rcpt_name)s" <%(rcpt_addr)s>
       
    99 Subject: %(subject)s
       
   100 Message-ID: <%(now)f.%(now)X@mailtb.%(host)s>
       
   101 Auto-Submitted: auto-generated
       
   102 MIME-Version: 1.0
       
   103 Content-Type: text/plain; charset=utf-8
       
   104 Content-Transfer-Encoding: 8bit
       
   105 """ % mail_config
       
   106     
       
   107     try:
       
   108         if mail_config['smtp_port'] != 465:
       
   109             smtp = smtplib.SMTP(mail_config['smtp_host'],
       
   110                     mail_config['smtp_port'])
       
   111             if mail_config['smtp_tls']:
       
   112                 smtp.starttls()
       
   113         else:
       
   114             smtp = smtplib.SMTP_SSL(mail_config['smtp_host'],
       
   115                     mail_config['smtp_port'])
       
   116         if len(mail_config['auth_user']) and len(mail_config['auth_pass']):
       
   117             smtp.login(mail_config['auth_user'], mail_config['auth_pass'])
       
   118         smtp.sendmail(mail_config['from_addr'], mail_config['rcpt_addr'],
       
   119                 '\n'.join((header, body)))
       
   120     except Exception, e:
       
   121         # try to log it (fire and forget)
       
   122         log_mail_error(e, mail_config['now'])
       
   123     finally:
       
   124         smtp.quit()
       
   125 
       
   126 def mailtbhook(extype, exval, extb):
       
   127     info = {}
       
   128     if type(extype) is type:
       
   129         info['extype'] = extype.__name__
       
   130     else:
       
   131         info['extype'] = str(extype).split("'")[1]
       
   132     if hasattr(exval, 'message'):
       
   133         info['message'] = exval.message if len(exval.message) else 'n/a'
       
   134     else:
       
   135         info['message'] = str(exval)
       
   136     info['traceback'] = ''.join(['%s\n' % l for l in traceback.format_tb(extb)])
       
   137     
       
   138     info['date'] = ctime()
       
   139     for k in ('HTTP_HOST', 'HTTP_REFERER', 'HTTP_USER_AGENT', 'REMOTE_ADDR',
       
   140              'REMOTE_PORT', 'REQUEST_METHOD', 'REQUEST_URI', 'SERVER_PROTOCOL'):
       
   141         info[k.split('_')[-1].lower()] = env[k] if env.has_key(k) else 'n/a'
       
   142 
       
   143     send_mail(info)
       
   144     send_error_page()
       
   145 
       
   146 def enable():
       
   147     sys.excepthook = mailtbhook