django代码中的电子邮件发送不起作用, 它显示错误“[Errno 10061]无法建立连接,因为目标机器主动拒绝它” 这些是我的 VIEWS.PY
def send_email(request):
username = request.POST.get('username', '')
from_email = request.POST.get('from_email', '')
message = request.POST.get('message', '')
if username and message and from_email:
try:
send_mail(username, from_email, message, ['canonizadocharm@ymail.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return HttpResponseRedirect('/contact/thanks/')
else:
# In reality we'd use a form class
# to get proper validation errors.
return HttpResponse('Make sure all fields are entered and valid.')
这些是我的 contact.html
<FORM METHOD="POST" ACTION="/send_email/" >
{% csrf_token %}
Name: <INPUT TYPE="text" NAME="username"><BR>
Email: <INPUT TYPE="text" NAME="from_email"><BR>
Message: <BR>
<TEXTAREA NAME="message" ROWS="10" WRAP="hard">
</TEXTAREA>
<INPUT NAME="redirect" TYPE="hidden">
<INPUT NAME="NEXT_URL" TYPE="hidden">
<BR>
<INPUT TYPE="submit" VALUE="Send">
<INPUT TYPE="reset" VALUE="Clear">
</FORM>
这些是 URLS.PY
url(r'^send_email/', views.send_email),
url(r'^contact/', views.contact),
url(r'^thanks/', views.thanks),
和我的 SETTINGS.PY
EMAIL_HOST = 'localhost'
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_PORT = 25
EMAIL_USE_TLS = True
答案 0 :(得分:3)
您的action
表单值必须指向查看网址,mailto:canonizadocharm@ymail.com
不是您服务器上的有效路径。
<强>已更新强>:
例如,向urls.py添加新规则,例如
url(r'^mail/', views.send_mail),
然后将操作值更改为mail
。
答案 1 :(得分:0)
让您的操作值指向一个网址,该网址又指向您的某个视图。例如,您的urls.py可以执行此操作。
url(r'^email/', 'project.views.send_email')
这会将您的联系表单发送到您的send_mail视图。
答案 2 :(得分:0)
模板中的表单没有csrf,这就是“CSRF验证失败”错误的原因。
<FORM METHOD=POST ACTION="/send_email/" ENCTYPE="text/plain">{% csrf_token %}
...........
</FORM>
如果您想知道什么是csrf,请转到此链接:
https://docs.djangoproject.com/en/dev/ref/contrib/csrf/
在您的settings.py中创建电子邮件设置,例如:
<强> settings.py 强>
# Sending mail
EMAIL_USE_TLS = True
EMAIL_HOST='smtp.gmail.com'
EMAIL_PORT=587
EMAIL_HOST_USER='your gmail account'
EMAIL_HOST_PASSWORD='your gmail password'
<强> views.py 强>
from django.core.mail import send_mail
def send_email(request):
if request.method == 'POST':
username = request.POST.get('username')
message = request.POST.get('message')
from_email = request.POST.get('from_email')
send_mail(username, message, from_email, ['canonizadocharm@ymail.com',])
return HttpResponseRedirect('/contact/thanks/')
else:
return HttpResponse('Make sure all fields are entered and valid.')