Adding a Dynamic Email Backend in Django

折月煮酒 提交于 2020-12-29 06:37:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!