问题
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