Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a Dynamic Email Backend in Django

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.

like image 551
creyD Avatar asked Dec 02 '20 10:12

creyD


People also ask

How to send email in django rest framework?

Inside of the “send_mail.py”, create a function that takes in the following arguments. def send_mail(html,text='Email_body',subject='Hello word',from_email='',to_emails=[]): The next step would be to make sure that the “to_emails” argument is always a “list of emails” and not a string or any other data type.

How to send multiple emails in django?

How to send multiple mass emails django. We need to create a Tuple of messages and send them using send mass mail. In this tutorial, we create a project which sends email using Django. We fill the data in the form and send it using Django Email.

How does Django get email?

With Django Admin Go to Django Admin, then to 'Mailboxes' page, check all the mailboxes you need to receive emails from. At the top of the list with mailboxes, choose the action selector 'Get new mail' and click 'Go'.


1 Answers

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.

like image 192
Martí Avatar answered Oct 17 '22 23:10

Martí