Search code examples
pythonemaildjango-settings

Setting up environmental variables in Python


Long time creeper, first time caller. I was trying to create and use environ var to send gmail (smtp) from a settings.py file, but clearly I was doing it wrong because when I put in my password it worked, but when I used os.environ.get to hide the password.

I think I didn't call the environmental variable correctly but I have no clue! I got an authentication error

import os

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'Thisworkedfine'

But when I used this it didn't work after defining 'EMAIL_USER' and 'EMAIL_PASS' in my System Properties.


EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = os.environ.get('EMAIL_USER')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS')

Error from hell:

SMTPSenderRefused at /password-reset/
(530, b'5.5.1 Authentication Required. Learn more at\n5.5.1  https://support.google.com/mail/?p=WantAuthError c2sm2597974pjs.13 - gsmtp', 'webmaster@localhost')

HALP!


Solution

  • One way is to set your variables in another python file and import the file.

    Create a file say,myEnvVal.py

    import os
    # Set environment variables
    def setVar():
        os.environ['EMAIL_USER'] = '[email protected]'
        os.environ['EMAIL_PASSWORD'] = 'Thisworkedfine'
    

    Now import this file

    import os
    import myEnvVal
    myEnvVal.setVar()
    EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
    EMAIL_HOST = 'smtp.gmail.com'
    EMAIL_PORT = 587
    EMAIL_USE_TLS = True
    EMAIL_HOST_USER = os.environ.get('EMAIL_USER')
    EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS')