Search code examples
pythondjangodjango-settings

How can I get the email configuration from the DB?


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?


Solution

  • 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()
       ....