Jason Howard
Jason Howard

Reputation: 1586

Overriding settings.py email settings in view

The email settings that are used by a post request need to depend on logic within my view. As a result, I'd like to overwrite the following email settings within my view, which are typically set in settings.py:

settings.py

EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = '****************'
DEFAULT_FROM_EMAIL = '[email protected]'
SERVER_EMAIL = '[email protected]'

Based on my reading (https://docs.djangoproject.com/en/2.1/topics/settings/#using-settings-without-setting-django-settings-module), I believe the best way to do this is as follows:

views.py

from django.conf import settings

def myview(request):

    profile = ..logic that grab's user's profile...

    settings.configure(EMAIL_HOST_USER = profile.email)
    settings.configure(EMAIL_HOST_PASSWORD = profile.email_password)
    settings.configure(DEFAULT_FROM_EMAIL = profile.email)
    settings.configure(SERVER_EMAIL = profile.email)

Can you confirm that this is the most appropriate way to do this?

Thanks!

Upvotes: 1

Views: 164

Answers (1)

Vaibhav Vishal
Vaibhav Vishal

Reputation: 7138

What you are doing should work, but it's not recommended to alter settings at runtime.

You can pass all these values when calling send_mail() so there is no need to modify settings. Just pass proper keyword arguments when sending the email.

You can also use the EmailMessage class to have more control.

You can create an object of EmailMessage like this:

# from Django docs
from django.core.mail import EmailMessage

email = EmailMessage(
    'Hello',
    'Body goes here',
    '[email protected]',
    ['[email protected]', '[email protected]'],
    ['[email protected]'],
    reply_to=['[email protected]'],
    headers={'Message-ID': 'foo'},
)

email.send()

See attached links to docs for more info.

Upvotes: 1

Related Questions