2012-01-06 5 views
5

私は電子メールを送信するためにサードパーティーを使用しています。それらを介して送信する電子メールにヘッダーを追加することで、電子メールを分類することができます。500が生成されたときにdjangoが管理者に送信する電子メールにヘッダーを追加することはできますか?

送信前に例外メールにヘッダーを追加することはできますか?少なくとも、私はミドルウェアで例外をキャッチして電子メールを送信することを管理しますが、djangoが私に500を送信する素晴らしい電子メール応答を生成するにはどうすればいいですか?

EDIT:メールにヘッダーを追加する方法を知っています。ミドルウェアで例外を処理する方法を知っています。私はdjangoが例外で送信するのと同じ電子メールを生成する方法に興味があるので、ヘッダを追加することができます。 (django.utils.logで定義)

答えて

8
  1. サブクラスAdminEmailHandler
  2. これに応じてloggingを設定します。ここで

はどのAdminEmailHandler作品:私の前の回答:参照用のみ

class AdminEmailHandler(logging.Handler): 
    """An exception log handler that emails log entries to site admins. 

    If the request is passed as the first argument to the log record, 
    request data will be provided in the email report. 
    """ 

    def __init__(self, include_html=False): 
     logging.Handler.__init__(self) 
     self.include_html = include_html 

    def emit(self, record): 
     try: 
      request = record.request 
      subject = '%s (%s IP): %s' % (
       record.levelname, 
       (request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS and 'internal' or 'EXTERNAL'), 
       record.msg 
      ) 
      filter = get_exception_reporter_filter(request) 
      request_repr = filter.get_request_repr(request) 
     except: 
      subject = '%s: %s' % (
       record.levelname, 
       record.getMessage() 
      ) 
      request = None 
      request_repr = "Request repr() unavailable." 

     if record.exc_info: 
      exc_info = record.exc_info 
      stack_trace = '\n'.join(traceback.format_exception(*record.exc_info)) 
     else: 
      exc_info = (None, record.getMessage(), None) 
      stack_trace = 'No stack trace available' 

     message = "%s\n\n%s" % (stack_trace, request_repr) 
     reporter = ExceptionReporter(request, is_email=True, *exc_info) 
     html_message = self.include_html and reporter.get_traceback_html() or None 
     mail.mail_admins(subject, message, fail_silently=True, html_message=html_message) 

  1. カスタムミドルウェアを作成します:
  2. process_responseを見て)https://code.djangoproject.com/browser/django/trunk/django/middleware/common.pyにはCommonMiddlewareからインスピレーションを取るここでhttps://code.djangoproject.com/browser/django/trunk/django/core/mail/message.py

に基づいて send_mail_with_exception_header機能を作成します。例を次に示します。

# Custom middleware 

class MyErrorMiddleware(object): 
    def process_response(self, request, response): 
     if response.status_code == 404: 
      domain = request.get_host() 
      referer = request.META.get('HTTP_REFERER', None) 
      is_internal = _is_internal_request(domain, referer) 
      path = request.get_full_path() 
       if referer and not _is_ignorable_404(path) and (is_internal or '?' not in referer): 
        ua = request.META.get('HTTP_USER_AGENT', '<none>') 
        ip = request.META.get('REMOTE_ADDR', '<none>') 
        mail_error("Broken %slink on %s" % ((is_internal and 'INTERNAL ' or ''), domain), 
         "Referrer: %s\nRequested URL: %s\nUser agent: %s\nIP address: %s\n" \ 
            % (referer, request.get_full_path(), ua, ip), 
            fail_silently=True) 
       return response 

# Custom mail_error function 

def mail_error(subject, message, fail_silently=False, connection=None, 
        html_message=None): 
    """Sends a message to the managers, as defined by the MANAGERS setting.""" 
    if not settings.MANAGERS: 
     return 

    # put your extra headers here 
    mail = EmailMultiAlternatives(u'%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject), 
       message, settings.SERVER_EMAIL, [a[1] for a in settings.MANAGERS], 
       connection=connection, header={}) 
    mail 
    if html_message: 
     mail.attach_alternative(html_message, 'text/html') 
    mail.send(fail_silently=fail_silently) 
+0

私はこれを理解していますが、通常は管理者例外メールで送信される素晴らしいデータをどのように生成しますか? – MattoTodd

+0

申し訳ありません。私はAdminEmailHandlerで私の答えを更新しました。これはDjangoがどのようにしているかを示しています。 – charlax

+0

私は現在django.utils.logモジュールを持っていないdjango 1.2を実行していますが、これは1.2のどこに存在していますか? – MattoTodd

関連する問題