Send email using environment variables via Django for security

时光总嘲笑我的痴心妄想 提交于 2019-12-14 03:08:27

问题


I can send emails using environment variables in my settings.py, however how do I input these variables in views.py? When put the actual email in str--it works; but for extra security, I written it as env. variable and gave me an error: SMTPRecipientsRefused. Also, how do I get it to show the sender's email. It shows in the console, but not when I receive the email. I am trying to get different users to send to one email recipient as contact form.

settings.py:

SECRET_KEY = os.environ.get('SECRET_KEY')
EMAIL_HOST_USER=os.environ.get('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD=os.environ.get('EMAIL_HOST_PASSWORD')

views.py:

def contact(request):
  message = request.POST.get('message', '')
  from_email = request.POST.get('from_email', '')

  send_mail('Contact Form', message, from_email, ['EMAIL_HOST_USER'])
  return render(request, 'first_app/contact.html')

contact.html:

<form action="/contact" method="POST">
  {% csrf_token %}
  <input type="email" name="from_email" placeholder="Your email">
  <textarea name="message" placeholder="Message...">
  </textarea>
  <input type="submit"/>
</form>

回答1:


To use your project's settings in views.py you need to import the object django.conf.settings.

Change your views.py to:

from django.conf import settings

def contact(request):

    if request.method == 'POST':
        message = request.POST.get('message', '')
        from_email = request.POST.get('from_email', '')
        send_mail('Contact Form', message, from_email, [settings.EMAIL_HOST_USER])

    return render(request, 'first_app/contact.html')


来源:https://stackoverflow.com/questions/55660083/send-email-using-environment-variables-via-django-for-security

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!