Python新手使用的Django架站的16堂课 — 第八章(三)
django发送邮件
官网文档:https://docs.djangoproject.com/en/dev/topics/email/
关于setting的文档https://docs.djangoproject.com/en/dev/ref/settings/
书中使用Mailgun的邮件收发服务,但是由于网内网络无法进行注册(正常网络无法进行人机验证),所以采用了django自带的邮件发送模块。
采用:163邮箱发送到qq邮箱
settings.py
# -*- coding: utf-8 -*-
"""
Django settings for test001 project.
Generated by 'django-admin startproject' using Django 1.11.29.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'hmsx_+*eh@$+%_zkp#%t-448b^r0^c0h+zrld$@3o2@^ku6hz$'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'simpleui',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'testdb',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'test001.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'test001.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
'''
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
'''
DATABASES = {
'default':{
'ENGINE':'django.db.backends.mysql',
'NAME':'mydb',
'USER':'root',
'PASSWORD':'Root123!@#',
'HOST':'localhost',
'PORT':'',
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR,'static')]
# 设置邮件域名
EMAIL_HOST = 'smtp.163.com'
# 设置端口号,为数字
EMAIL_PORT = 25
#设置发件人邮箱
EMAIL_HOST_USER = '自己的邮箱@163.com'
# 设置发件人 授权码
EMAIL_HOST_PASSWORD = '邮箱密码'
# 设置是否启用安全链接
EMAIL_USER_TLS = True
# 以上这个配置信息,Django会自动读取,
# 使用账号以及授权码进行登录,
# 如果登录成功,可以发送邮件
views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from django.template.loader import get_template
from django.http import HttpResponse
from testdb import models,forms
from django.template import RequestContext,Context,Template
from django.core.mail import send_mail,send_mass_mail,EmailMultiAlternatives
from django.conf import settings
# Create your views here.
def posting(request):
template = get_template('posting.html')
moods = models.Mood.objects.all()
message = '如果要发布信息,那么每个字段都要填写...'
# request_context = RequestContext(request)
# request_context.push(locals())
# #html = template.render(request_context)
html = template.render(context=locals(),request=request)
# html = template.render(locals())
return HttpResponse(html)
def index(request,pid=None,del_pass=None):
template = get_template('index.html')
posts = models.Post.objects.filter(enabled=True).order_by('-pub_time')[0:30]
moods = models.Mood.objects.all()
try:
user_id=request.GET['user_id']
user_pass=request.GET['user_pass']
user_post=request.GET['user_post']
user_mood=request.GET['mood']
except:
user_id=None
message='如果要发布信息,那么每个字段都要填写...'
if del_pass and pid:
try:
post = models.Post.objects.get(id=pid)
except:
post = None
if post:
if post.del_pass == del_pass:
post.delete()
message = '数据删除成功'
else:
message = '密码错误'
elif user_id != None and user_id != '':
mood=models.Mood.objects.get(status=user_mood)
post = models.Post.objects.create(mood=mood,nickname=user_id,del_pass=user_pass,message=user_post)
post.save()
message='成功存储!请记得你的编辑密码[{}]!,信息须经审核后才会显示。'.format(user_pass)
else:
message='如果要发布信息,那么每个字段都要填写...'
html = template.render(locals())
return HttpResponse(html)
def alert(request):
template = get_template('alert.html')
html = template.render()
return HttpResponse(html)
def listing(request):
template = get_template('listing.html')
posts = models.Post.objects.filter(enabled=True).order_by('-pub_time')[0:50]
moods = models.Mood.objects.all()
html = template.render(locals())
return HttpResponse(html)
def contact(request):
if request.method =='POST':
form = forms.ContactForm(request.POST)
if form.is_valid():
message = '感谢您的来信,我们会尽快处理您的宝贵意见。'
user_name = form.cleaned_data['user_name']
user_city = form.cleaned_data['user_city']
user_school = form.cleaned_data['user_school']
user_email = form.cleaned_data['user_email']
user_message = form.cleaned_data['user_message']
email_subject = u'来自【不吐不快】网站的网友意见'
email_body = u'''
网友姓名:{}
居住城市:{}
是否在学:{}
反映意见:如下
{}'''.format(user_name,user_city,user_school,user_message)
#email_from = '自己的发送邮箱@163.com'
email_from = settings.EMAIL_HOST_USER
email_to = ['自己的接收邮箱@qq.com',]
res = send_mail(email_subject,email_body,email_from,email_to,fail_silently=False)
if res == 1:
message = '邮件发送成功!'
else:
message = '邮件发送失败'
else:
message = '请检查您输入的信息是否正确!'
else:
form = forms.ContactForm()
template = get_template('contact.html')
request_context = RequestContext(request)
request_context.push(locals())
#html = template.render(request_context)
html = template.render(context=locals(),request=request)
return HttpResponse(html)
forms.py
# -*- coding: utf-8 -*-
from django import forms
class ContactForm(forms.Form):
CITY = [['TP','TaiPei'],['TY','TaoYuang'],['TC','TaiChuang'],['TN','TaiNan'],['KS','Kaohsiung'],['NA','Others'],]
user_name = forms.CharField(label="您的姓名",max_length=50,initial='无名')
user_city = forms.ChoiceField(label='居住城市',choices=CITY)
user_school = forms.BooleanField(label='是否在学',required=False)
user_email = forms.EmailField(label='电子邮件')
user_message = forms.CharField(label='你的意见',widget=forms.Textarea)
contact.html
<!-- contact.html(ch08www project) -->
{% extends 'base.html' %}
{% block title %}网络管理员{% endblock %}
{% block content %}
{% if message %}
<div class='alert alert-warning'>{{message}}</div>
{{user_name}}<br/>
{{user_city}}<br/>
{{user_school}}<br/>
{{user_email}}<br/>
{{user_message | linebreaks }}<br/>
{% endif %}
<div class='container'>
<div class='panel panel-primary'>
<div class='panel-heading'>
<form name='my form' action='.' method='POST'>
{% csrf_token %}
<h3>写信给管理员</h3>
</div>
<div class='panel-body'>
{{ form.as_p }}
</div>
<div class='panel-footer'>
<input type='submit' value='提交'>
</div>
</form>
</div>
</div>
{% endblock %}
urls.py
from django.conf.urls import url
from django.contrib import admin
from testdb import views
urlpatterns = [
url(r'^$',views.index),
url(r'^alert/$',views.alert),
url(r'^admin/', admin.site.urls),
url(r'^(\d+)/(\w+)/$',views.index),
url(r'^list/$',views.listing),
url(r'^post/$',views.posting),
url(r'^contact/$',views.contact),
实测结果: