问题
I would like to let my users decide their email backend on their own. That is why I have created the email relevant keys (host, port, username...) on the users and now I try to work this (see below) backend into my Django project. Working with the docs and the source code, my first attempt was to extend the default EmailBackend by my custom "UserBackend" which overrides the __init__ function like this:
class UserBackend(EmailBackend):
def __init__(self, user_id, host=None, port=None, username=None ...):
user = User.objects.get(id=user_id)
super().init(host=user.email_host, port=user.email_port ...)
As this method is called (I tried to send_mail from the shell) it gets no user_id. How can I approach this differently or how would I extend my attempts to do this? I wouldn't want to rewrite Djangos mail system entirely, as it works in itself.
回答1:
send_email has a parameter called connection (link to docs) which seems to fit perfectly. You can get a connection by calling get_connection (link to docs) with the user's parameters.
connection = get_connection(host=user.email_host, port=user.email_port, ...)
send_email(connection=connection, ...)
If you'd like to support multiple backend types, get_connection also supports it.
来源:https://stackoverflow.com/questions/65106184/adding-a-dynamic-email-backend-in-django