问题
Is it possible to replace calls to django.core.mail.send_mail()
across my entire project (including third-party projects in my INSTALLED_APPS) with a custom send_mail()
?
I'm integrating django-mailer with my project, which provides a replacement send_mail()
for django.core.mail.send_mail()
. Since both use the same function signature the docs suggest importing the django-mailer version in places where you'd normally import the Django-provided version like so:
# favour django-mailer but fall back to django.core.mail
from django.conf import settings
if "mailer" in settings.INSTALLED_APPS:
from mailer import send_mail
else:
from django.core.mail import send_mail
This works for my own app code, but I'd also like to make the same changes across third-party apps that use django.core.mail.send_mail()
. Right now, I hit errors when these apps try to send e-mail.
Does Django provide any kind of hook to replace django.core.mail.send_mail()
, or is there a workaround? Right now I'm looking at forking each third-party project that sends e-mails and adding the conditional import code above, but that is obviously not ideal.
回答1:
Django has email backends that let you override the way that emails from django.core.mail
are sent, instead of going through SMTP. There are some that let you save them locally and so on; django-mailer
also includes one (as described in usage.txt) to do exactly what you want to do.
来源:https://stackoverflow.com/questions/11919118/replace-django-core-mail-send-mail-across-all-apps