如何在Django中记录所有外发邮件?

pexxcrt2  于 2023-04-07  发布在  Go
关注(0)|答案(4)|浏览(91)

我的Django应用程序发送了相当多的电子邮件,我已经尝试过彻底测试它。然而,在最初的几个月里,我想记录所有外发的电子邮件,以确保一切顺利。
有没有一个Django模块可以让我做到这一点,并使传出的电子邮件通过管理面板可见?

cqoc49vn

cqoc49vn1#

我写了一个自定义的电子邮件后端日志的东西到一个模型。
这是我的后端:

from django.core.mail.backends.smtp import *
from django.db import transaction

from modules.common.models import *

class LoggingEmailBackend(EmailBackend):
    """
    A wrapper around the SMTP backend that logs all emails to the DB.
    """
    def send_messages(self, email_messages):
    """
    A helper method that does the actual logging
    """
    with transaction.commit_on_success():

        for email_message in email_messages:

            email_record = Email.objects.create(
                to='; '.join(email_message.recipients()),
                subject=email_message.subject, body=email_message.body,
            )

            try:
                return super(LoggingEmailBackend, self)._send(
                    email_message
                )
            except:
                email_record.ok = False
                return False
            finally:
                email_record.ok = True
                return True

下面是模型:

class Email(models.Model):
    """
    Model to store all the outgoing emails.
    """
    when = models.DateTimeField(
        null=False, auto_now_add=True
    )
    to = models.EmailField(
        null=False, blank=False,
    )
    subject = models.CharField(
         null=False, max_length=128,
    )
    body = models.TextField(
        null=False, max_length=1024,
    )
    ok = models.BooleanField(
        null=False, default=True,
    )

这是我的模型:

from django.contrib import admin

from modules.common.models import *

class EmailAdmin(admin.ModelAdmin):
    """
    Admin part for managing the the Email model
    """
    list_display = ['to', 'subject', 'ok',]
    list_filter = ['ok']
    readonly_fields = ['when', 'to', 'subject', 'body', 'ok']
    search_fields = ['subject', 'body', 'to']

    def has_delete_permission(self, request, obj=None):
        return False

    def has_add_permission(self, request):
        return False

admin.site.register(Email, EmailAdmin)
3ks5zfa0

3ks5zfa02#

由于OP询问的是日志记录而不是保存到数据库,因此这里有一个中间件:

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)

然后在您的settings.py:

EMAIL_BACKEND = 'whereiputit.LoggingBackend'
ux6nzvsh

ux6nzvsh3#

我不知道是否存在这样的模块,但编写一个自定义的是小菜一碟。只需创建一个单独的模型,每次发送电子邮件时,创建一个新的示例(使用自定义方法发送电子邮件)。然后,将此模型与管理员和宾果链接。

sdnqo3pr

sdnqo3pr4#

Django提供了自定义的电子邮件后端,你可以自己编写一个。

相关问题