Friday, October 1, 2021

thumbnail

How to configure email from DB in django

 

How to configure email from Database in django


In most of the django projects email is configured from the settings.py file present on the project folder. But in some cases we may need to configure the email taking the username and password from the database. In settings.py if we fetch any data from any of the database model it will show error. Because when the server is run it reads the settings.py file first and it has no knowledge of the models at this stage. For this reason it shows error. Therefore we have to find some other way to solve that.

To solve this issue we will not configure email from the settings.py file. Rather we will make a custom email back end inside views.py which will return a connection. We can send email using this connection.
At first comment out the email configuration in settings.py file (If you have made in earlier).Then create a model inside models.py which will containing all the necessary fields.


models.py

from django.db import models

class Email_address(models.Model):

    email_host = models.CharField(max_length=200, null=True)

    email_port = models.PositiveBigIntegerField(null=True)

    email_host_user = models.CharField(max_length=200, null=True)

    from_email = models.CharField(max_length=200, null=True)

    email_host_password = models.CharField(max_length=200, null=True)




Now make an Email_address object with the necessary information in the database.

After this we have to make a connection function inside the views.py file.



views.py

from .models import *

from django.core.mail import get_connection, send_mail

def connection():

    e = Email_address.objects.first()


    my_host = e.email_host

    my_port = e.email_port

    my_username = e.email_host_user

    my_password = e.email_host_password

    my_use_tls = True

    connection = get_connection(host=my_host,

        port=my_port,

        username=my_username,

        password=my_password,

        use_tls=my_use_tls)

    return connection


Now we can use it where ever we need to send email using the following code.


views.py for Sending Email:


from django.core.mail import get_connection, send_mail

e = Email_address.objects.first()

def sendemail(request):

    send_mail(

    ‘This is the subject.’,

    ‘This is the main template’,

    e.from_email,

    [emailtobesent@email.com],

    connection=connection()

    )




This is how we can configure email from database easily in django.

Subscribe by Email

Follow Updates Articles from This Blog via Email

No Comments