通过Django使用环境变量发送电子邮件以确保安全 [英] Send email using environment variables via Django for security
问题描述
我可以在settings.py中使用环境变量发送电子邮件,但是如何在views.py中输入这些变量?当将实际的电子邮件放入str时,它可以工作;但是为了提高安全性,我将其编写为env.变量并给我一个错误:SMTPRecipientsRefused.另外,如何获取它以显示发件人的电子邮件.它会显示在控制台中,但不会在我收到电子邮件时显示.我试图让不同的用户以联系表的形式发送给一位电子邮件收件人.
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:
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:
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>
推荐答案
要在views.py中使用项目的设置,您需要导入对象django.conf.settings.
To use your project's settings in views.py you need to import the object django.conf.settings.
将您的views.py更改为:
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')
这篇关于通过Django使用环境变量发送电子邮件以确保安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!