Django之邮件发送

settings.py

#settings 添加如下配置进行邮件发送 
#邮件服务器
EMAIL_HOST = "smtp.qq.com"
#邮件发送的端口
EMAIL_PORT = 25
#邮件发送者
EMAIL_HOST_USER = "xxx@doman.com"
#邮件发送者的密码
EMAIL_HOST_PASSWORD = "password"
#tls 加密
EMAIL_USE_TLS = True

forms.py

#coding:utf-8
__author__ = 'similarface'
from django import forms class EmailPostForm(forms.Form):
name=forms.CharField(max_length=25,label='姓名 ')
email=forms.EmailField()
to=forms.EmailField()
comments=forms.CharField(required=False,widget=forms.Textarea,label='备注')

views.py

#coding:utf-8
from django.shortcuts import render
#404
from django.shortcuts import get_object_or_404
#分页模块
from django.core.paginator import PageNotAnInteger,EmptyPage,Paginator
# Create your views here.
from .models import Post
from django.views.generic import ListView
from .forms import EmailPostForm
#邮件模块
from django.core.mail import send_mail
#不加以下3行 发送邮件的时候有中文在里面会报错
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
def post_share(request,post_id):
'''
文章分享 发送邮件
'''
post=get_object_or_404(Post,id=post_id,status='published')
sent=False
if request.method=='POST':
form=EmailPostForm(request.POST)
if form.is_valid():
cd=form.cleaned_data
post_url=request.build_absolute_uri(post.get_absolute_url())
subject = '{} ({}) 推荐你阅读 "{}"'.format(cd['name'], cd['email'], post.title)
message = '阅读: "{}" 地址: {}\n\n{}\ 备注: {}'.format(post.title, post_url, cd['name'], cd['comments'])
#这儿的xxx@doman.com 要和settings.py的EMAIL_HOST_USER 对应 [cd['to'] 接受邮件的列表]
send_mail(subject, message, 'xxx@doman.com',[cd['to']])
sent = True
else:
form=EmailPostForm()
return render(request, 'myblog/post/share.html', {'post': post,'form': form,'sent': sent})

html:

{% extends "myblog/base.html" %}
{% block title %}Share a post{% endblock %}
{% block content %}
{% if sent %}
<h1>邮件发送成功</h1>
<p>
"{{ post.title }}" 已经成功发送到 {{ cd.to }}.
</p>
{% else %}
<h1>分享文章 "{{ post.title }}" </h1>
<form action="." method="post">
{{ form.as_p }}
{% csrf_token %}
<input type="submit" value="发送邮件">
</form>
{% endif %}
{% endblock %}

Django之邮件发送

Django之邮件发送  

上一篇:虚幻4外包团队-推荐非常全面的的Unreal教程


下一篇:jquery滚动元素