7

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 Answer 1

4
+50

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Sounds good, I will test this later. Thanks for your answer!
This seems to work! Thank you very much, do you know how this stands in regards to best practices?
This is simply using a public and documented part of the Django API. They may change the API in the future but I think they won't because there no reason to.
I know, I wanted to wait if there were any other answers but I guess there aren't. Thanks again @Martí

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.