利用表单发送邮件
前提:配置settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = False
EMAIL_HOST = 'smtp.126.com' # 主机
EMAIL_PORT = 25 # 端口
EMAIL_HOST_USER = 'xxxxxxxxx@126.com' # 发件人邮箱
EMAIL_HOST_PASSWORD = 'xxxxxxx' # 密码
DEFAULT_FROM_EMAIL = 'mail@126.com' # 发件人
1.forms.py
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField()
from_email = forms.EmailField() # 发件方
to_email = forms.EmailField() # 收件方
message = forms.CharField()
对应的url模式为:
url(r'^contact/$', contact)
对应的表单样式为:
![](https://images2017.cnblogs.com/blog/1055519/201707/1055519-20170727113236718-1198601955.png)
在上图中收件方利用qq邮箱失败,但可以利用126和outlook邮箱。
2.views.py
from django.core.mail import send_mail
from django.shortcuts import render_to_response
from contact.forms import ContactForm
from django.http import HttpResponseRedirect, HttpResponse
from django.template import RequestContext
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
send_mail( # 调用django库中的send_main函数
cd['subject'], # 主题
cd['message'], # 内容
cd.get('from_email'), # 发件人
[cd.get('to_email')] # 收件人列表
)
return HttpResponseRedirect('/contact/thanks/') # 发送成功则重定向到thanks页面
else:
form = ContactForm() # 失败则为空表单
return render_to_response('contact_form.html', {'form': form}, context_instance=RequestContext(request)) # 发送失败则返回表单页面
def thanks(request):
html = "<html><body><strong>Thanks</body></html>" # 简单的页面显示Thanks
return HttpResponse(html)
url(r'^contact/thanks/$', thanks)为感谢页面url
3.contact_form.html
<html>
<head>
<title>Contact us</title>
</head>
<body>
<h1>Contact us</h1><form action="" method="post">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" value="Submit">
</form>
</body>
</html>
4.发送结果
![](https://images2017.cnblogs.com/blog/1055519/201707/1055519-20170727114750906-28133938.png)
![](https://images2017.cnblogs.com/blog/1055519/201707/1055519-20170727114705984-637862303.png)
5.流程解释
首先访问contact/时,urls将其指向views.py中的contact函数(由语句url(r'^contact/$', contact))实现。
因为此时没有提交任何东西,所以语句 request.method=='POST'不成立,直接执行 form = ContactForm()语句,并返回 contact_form.html页面。
此时填写好表单提交后,若数据合法则送邮件,然后执行语句重定向到 /contact/thanks 网页。若数据不合法,则在contact_form.html页面上保留有填好的错误表单,并有错误提示(见下图)。