How can I log all outgoing email in Django?

前端 未结 4 2173
被撕碎了的回忆
被撕碎了的回忆 2021-02-20 00:28

My Django application sends out quite a bit of emails and I\'ve tried testing it thoroughly. However, for the first few months, I\'d like to log all outgoing emails to ensure th

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-20 01:05

    Since the OP asked about logging and not about saving to DB, here's a middleware that does that:

    import django.core.mail.backends.smtp
    import logging
    
    logger = logging.getLogger(__name__)  # or you could enter a specific logger name
    
    class LoggingBackend(django.core.mail.backends.smtp.EmailBackend):
    
      def send_messages(self, email_messages):
        try:
            for msg in email_messages:
                logger.info(u"Sending message '%s' to recipients: %s", msg.subject, msg.to)
        except:
            logger.exception("Problem logging recipients, ignoring")
    
        return super(LoggingBackend, self).send_messages(email_messages)
    

    and then in your settings.py:

    EMAIL_BACKEND = 'whereiputit.LoggingBackend'
    

提交回复
热议问题