跟随Django Book的内容发送邮件不成功,总结一下需要配置好settings.py文件,还要注意一些细节。
1、在settings文件最后添加以下内容,缺一不可!
EMAIL_HOST= 'smtp.163.com'
EMAIL_PORT= 25
EMAIL_HOST_USER = 'xxxxxx@163.com'(你有163邮箱的话)
EMAIL_HOST_PASSWORD = ‘xxxxxxx'
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
这里Host邮箱最好还是写163的,qq的我试过不行,别的也不敢保证可以。如果出现“STARTTLS extension not supported by server”这种错误类型很有可能是邮箱不支持。
2、出现Forbidden (403)“CSRF verification failed. Request aborted.”的错误
需要添加{% csrf_token %}到form中去,<form action="/contact/" method="post">{% csrf_token %}<p>...</p>...</form>
之后在contact()方法的views.py中添加from django.template import RequestContext并且最后一句改为return render_to_response('contact_form.html',{'errors': errors}, context_instance=RequestContext(request))即可
3、我的目录结构是这样的:
mysite-->
books/
contact/
mysite/
templates/
manage.py
4.最后附上完整代码
templates/contact_form.html文件如下
-
<html>
-
<head>
-
<title>Contact us</title>
-
</head>
-
<body>
-
<h1>Contact us</h1>
-
-
{% if errors %}
-
<ul>
-
{% for error in errors %}
-
<li>{{ error }}</li>
-
{% endfor %}
-
</ul>
-
{% endif %}
-
-
<form action="/contact/" method="post">{% csrf_token %}
-
<p>Subject: <input type="text" name="subject"></p>
-
<p>Your e-mail (optional): <input type="text" name="email"></p>
-
<p>Message: <textarea name="message" rows="10" cols="50"></textarea></p>
-
<input type="submit" value="Submit">
-
</form>
-
</body>
-
</html>
contact/views.py文件如下:
-
from django.core.mail import send_mail
-
from django.http import HttpResponseRedirect
-
from django.shortcuts import render
-
from django.template import RequestContext
-
def contact(request):
-
errors = []
-
if request.method == 'POST':
-
if not request.POST.get('subject', ''):
-
errors.append('Enter a subject.')
-
if not request.POST.get('message', ''):
-
errors.append('Enter a message.')
-
if request.POST.get('email') and '@' not in request.POST['email']:
-
errors.append('Enter a valid e-mail address.')
-
if not errors:
-
send_mail(
-
request.POST['subject'],
-
request.POST['message'],
-
request.POST.get('email', 'noreply@example.com'),
-
['接收信件的邮箱!'],
-
)
-
return HttpResponseRedirect('/contact/thanks/')
-
return render(request, 'contact_form.html',
-
{'errors': errors},context_instance=RequestContext(request))
mysite/mysite/urls.py如下:
-
from django.conf.urls import *
-
from django.contrib import admin
-
from books import views
-
from mysite.views import emailsuccess
-
from contact.views import contact
-
admin.autodiscover()
-
-
urlpatterns = patterns('',
-
(r'^contact/$',contact),
-
(r'^contact/thanks/$',emailsuccess),
-
)
mysite/mysite/views.py文件如下:
-
from django.http import HttpResponse,Http404
-
def emailsuccess(request):
-
return HttpResponse("Send Succeed!")
欢迎交流讨论,共同学习!
转载请注明出处:http://blog.csdn.net/monkeyduck