我的Django应用程序发出了相当多的电子邮件,我已经尝试过彻底测试了。但是,在最初几个月,我想记录所有外发电子邮件,以确保一切顺利。是否有一个Django模块允许我这样做,并通过管理面板显示外发电子邮件
感谢。
答案 0 :(得分:9)
我编写了一个自定义电子邮件后端,将内容记录到模型中。
这是我的后端:
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)
答案 1 :(得分:3)
由于OP询问了日志记录而不是保存到DB,所以这是一个中间件:
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'
答案 2 :(得分:2)
Django提供自定义电子邮件后端you can write one on your own。
答案 3 :(得分:1)
我不知道是否存在以这种方式工作的模块,但编写自定义模块是件小事。只需创建一个单独的模型,每次发送电子邮件时,都要创建一个新实例(使用自定义方法进行电子邮件发送)。然后,将此模型与admin和bingo链接..