How can I get the email configuration from the DB?

Question:

What I need is to take the email configuration like EMAIL_HOST_USER, EMAIL_HOST, EMAIL_PORT, etc. From my database and then pass that values to the email configuration in the settings.py file. Is this possible? and if is, how can I do it?

Asked By: M. Gar

||

Answers:

Actualy this isn’t so hard to do if you use django.core.mail.backends.smtp.EmailBackend like this:

from django.core.mail.backends.smtp import EmailBackend

backend = EmailBackend(host = server.host, server.port, server.username, serer.password)

Once you create a backend like this. You have two options on how to send the message. The first is you can call the send_messages() method on it send your messages (or message). The second is you can tell EmailMessage to use it as the connection.
And where does server.whatever come from? The database of course.

class EmailServer(models.Model):
   host = models.CharFields()
   ....
Answered By: e4c5

Although this is more than six years old this gave me the right idea and it still works with Django 4.1. I also need the use_tls setting, so my setup looks like this:

from django.core.mail.backends.smtp import EmailBackend


# Get email settings from DB, e.g.
settings = Setting.objects.filter(name='settings').first()

# Custom email backend
backend = EmailBackend(
    host=settings.email_host,
    use_tls=settings.email_use_tls,
    port=settings.email_port,
    username=settings.email_host_user,
    password=settings.email_host_password_enc,
)

You can also continue using Django’s send_mail method, you might have been using before, if you pass in the custom backend for ‘connection’ (I had been using the following Thread class and just added the custom backend):

from django.core.mail import send_mail
from threading import Thread    


thread = MailThread(subject, mail_text, noreply, email)
thread.start()


class MailThread(Thread):
    def __init__(self, subject, mail_text, noreply, to_email):
        super(MailThread, self).__init__()
        self.subject = subject
        self.to_email = to_email
        self.noreply = noreply
        self.mail_text = mail_text

    # run method is automatically executed on thread.start()
    def run(self):
        send_mail(
            self.subject,
            self.mail_text,
            self.noreply,
            [self.email],
            fail_silently=False,
            connection=backend
        )
Answered By: pyphil
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.