Search code examples
pythondjangopython-3.xsendgrid

Send email using django without a settings file


Is it possible to do something like the following using the utility django sendmail?

>>> import os
>>> from django.core.mail import send_mail
>>> os.environ['EMAIL_BACKEND'] = 'django.core.mail.backends.smtp.EmailBackend'
>>> os.environ['EMAIL_HOST'] = 'smtp.sendgrid.net'
... etc.
>>> send_mail(
...     'Subject here',
...     'Here is the message.',
...     'from@example.com',
...     ['to@example.com'],
...     fail_silently=False,
... )

django.core.exceptions.ImproperlyConfigured: Requested setting EMAIL_BACKEND, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

If so, how could I do this?


Solution

  • Yes, you can use Django without a settings.py file. As the error message states, you'll have to call settings.configure() to manually configure settings.

    >>> from django.conf import settings
    >>> settings.configure(EMAIL_HOST='smtp.sendgrid.net', other_settings...)
    

    Pass the settings that you want to override to configure() function; otherwise Django will use the default values.


    See related docs for more: Using settings without setting DJANGO_SETTINGS_MODULE.