How to send mail using Django
This article is about how to use Django to send emails. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Django to send mail needs to use the module from django.core.mail import send_mail,send_mass_mailSMTP as the mail server, each mailbox smtp server address is different, such as Baidu 163mailbox is smtp.163.com
First, add configuration to settings
TEMPLATES = [{'BACKEND':' django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join (BASE_DIR,' templates')], # 'DIRS': [],' 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',],},} ] # Mail configuration EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'EMAIL_USE_TLS = True # whether to use the TLS secure transfer protocol (used to provide confidentiality and data integrity between two communication applications. EMAIL_USE_SSL = False # whether to use SSL encryption, qq enterprise mailbox requires the SMTP server of the mailbox that uses EMAIL_HOST = 'smtp.163.com' # to send mail 163mailbox EMAIL_PORT = 25 # outbox SMTP server port EMAIL_HOST_USER ='# @ 163.com' # email address EMAIL_HOST_PASSWORD = 'pwd'DEFAULT_FROM_EMAIL =' zjw 'STATIC_URL =' / static/'STATICFILES_DIRS = [os.path.join (BASE_DIR, 'static')] # the following options Means to hand over the session object to redis management SESSION_ENGINE = "django.contrib.sessions.backends.cache" SESSION_CACHE_ALIAS = "default"
Add configuration in urls
From django.contrib import adminfrom django.conf.urls import include, urlurlpatterns = [url ('admin/', admin.site.urls), url (ringing Votingbread itemsPlacement, include (' news.urls',namespace='voting')),] the above configuration enables you to use # @ 163.com mailbox to send mail.
Second, how to send
Write template files
From django.db import modelsfrom django.contrib.auth.models import User#Create your models here.class MyUser (User): # inherit the USer model class that comes with Django and rewrite url = models.URLField (blank=True, null=True, default= "http://www.baidu.com") class Meta (): verbose_name =" user "verbose_name_plural = verbose_name
Register with admin
From django.contrib import admin
From .models import *
# Register your models here.
Admin.site.register (MyUser)
Generate migration files and create tables in the database
Python manage.py makemigrations
Python manage.py migrate
Write a route
From django.conf.urls import urlfrom. Import viewsapp_name= 'voting'urlpatterns = [# CAPTCHA url (r' ^ verify/$', views.verify, name='verify'), # register url (r'^ regist/$',views.regist,name='regist'), # email url (r'^ active/ (. *?) / $', views.active,name='active'),]
Authoring views
The view function is as follows
1. Install itsdangerous
Pip install itsdangerous
2. Serialization
From itsdangerous import TimedJSONWebSignatureSerializer as Serializer,SignatureExpired
# email from django.core.mail import send_mail, send_mass_mail, EmailMultiAlternativesfrom django.conf import settingsimport random,io# to introduce serialization encryption and expiration information from itsdangerous import TimedJSONWebSignatureSerializer as Serializer,SignatureExpiredfrom django.shortcuts import renderfrom django.http import HttpResponsefrom .models import MyUserdef regist (request): if request.method = = 'GET': return render (request) 'Voting_items/regist.html') if request.method = = "POST": username = request.POST.get ("username_regi") pwd = request.POST.get ("password_regi") pwd2 = request.POST.get ("password_regi_2") res = None try: MyUser.objects.get () users = MyUser.objects.get_by_natural _ key (username=username) if username= = str (users): res = "the user is registered" return render (request 'Voting_items/login.html', {"res": res}) except Exception as q: print (Q) if pwd! = pwd2: res = "password inconsistency" return render (request,' Voting_items/login.html', {"res": res}) else: res = "successfully registered, please activate within 2 hours." User = MyUser.objects.create_user (username= username, password=pwd, url = 'http://www.baidu.com') print (user.id,user.username,user.is_active) # defaults to inactive state after registering a user user.is_active = False user.save () # in order to prevent non-artificial activation Need to encrypt the activation address # serialization with validity # 1 to get the serialization tool serutil = Serializer (settings.SECRET_KEY,expires_in=7200) # 2 use the tool to serialize the dictionary object result = serutil.dumps ({"userid": user.id}). Decode ("utf-8") # print (result Type (result) mail = EmailMultiAlternatives ("click activate user", "Please click: click activate"% (result,), settings.DEFAULT_FROM_EMAIL, ['zjw505104341@163.com']) mail.content_subtype = "html" mail.send () return render (request,' Voting_items/login.html', {"res": res})
# encrypted data coexist in serutive
Def active (request,info): serutil = Serializer (settings.SECRET_KEY,expires_in=7200) try: obj = serutil.loads (info) print (obj ["userid"]) id = obj ["userid"] user = get_object_or_404 (MyUser, pk=id) user.is_active = True user.save () return redirect (reverse ('voting:login'), {"res": "activated successfully." }) except SignatureExpired as e: return HttpResponse ("expired")
# CAPTCHA
Def verify (request): # try: # with open ('1.pngdeclare,' wb') as f: # return HttpResponse (f.readable ()) # except Exception as e: # print (e) # return HttpResponse ("error") # each request CAPTCHA, you need to use pillow to construct an image and return # define variables Background color, width, height bgcolor = (random.randrange (20,100), random.randrange (20,100), random.randrange (20,100)) width = 100heigth = 35 # create picture object im = Image.new ('RGB', (width, heigth)) Bgcolor) # create brush object draw = ImageDraw.Draw (im) # call the brush's point () function to draw noise for i in range (0100): # Random get position xy = (random.randrange (0, width), random.randrange (0, heigth)) # Random get color fill = (random.randrange (0255), 255, random.randrange (0) ) # populate draw.point (xy, fill=fill) # define the optional value of CAPTCHA str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0qwertyuiopasdfghjklzxcvbnm' # randomly select four values as CAPTCHA rand_str =' 'for i in range (0,4): rand_str + = str1 [random.randrange (0, len (str1))] print (rand_str) # construct font object font = ImageFont.truetype (' cambriab.ttf') 23) fontcolor = (255,255), random.randrange (0,255)) # draw four words draw.text ((5,2), rand_str [0], font=font, fill=fontcolor) draw.text ((25,2), rand_str [1], font=font, fill=fontcolor) draw.text ((50,2), rand_str [2], font=font, fill=fontcolor) draw.text ((75,2), rand_str [3], font=font Fill=fontcolor) # release brush del draw request.session ['verifycode'] = rand_str f = io.BytesIO () im.save (f,' png') # return the picture data in memory to the client MIME type is picture png return HttpResponse (f.getvalue (), 'image/png')
Write the interface
I used the template inheritance. This is the login interface.
{% extends' Base.html'%} {% block title%} login interface {% endblock%} {% block body%} {% comment%} {% csrf_token%} {{lf}} {% csrf_token%} {{rf} {% endcomment%} login status: {{res}}
{% csrf_token%} Landing Page