首先要有一个发送验证码的邮箱,并设置授权其smtp,获取授权码,获取方式参见这里。生成四位验证码,通过smtp发送邮件。
def yanzhengma(request):
from_addr = '发送验证码邮箱账号'
password = '授权码'
a=request.GET
sid=a.get('sid')
sname=a.get('sname')
snum=a.get('snum')
sclass=a.get('sclass')
pwd=a.get('pwd')
to_addr = sid
smtp_server = 'smtp.163.com'
list_num = [1,2,3,4,5,6,7,8,9,0]
list_str = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','s','t','x','y','z']
veri_str = random.sample(list_str,2)
veri_num = random.sample(list_num,2)
veri_out = random.sample(veri_num + veri_str,4)
veri_res =str(veri_out[0]) + str(veri_out[1]) + str(veri_out[2]) + str(veri_out[3])
print(veri_res)
msg = MIMEText("您的标点啄木鸟注册验证码为:" +veri_res,'plain','utf-8')
msg['From'] = Header(from_addr)
msg['To'] = Header(to_addr)
msg['Subject'] = Header('标点啄木鸟验证码')
server = smtplib.SMTP_SSL(smtp_server)
server.connect(smtp_server,465)
server.login(from_addr, password)
server.sendmail(from_addr, to_addr, msg.as_string())
server.quit()
selfinfo={}
selfinfo['sid']=sid
selfinfo['sname']=sname
selfinfo['snum']=snum
selfinfo['sclass']=sclass
selfinfo['pwd']=pwd
selfinfo['yanzhengma']=veri_res
return render(request,'*.html',selfinfo)
注册与之前相比添加了验证码比对,验证码正确且邮箱未注册过才能注册成功。
def save(request):
isregistered=0
a=request.GET
sid=a.get('sid')
if validateEmail(sid)==0:
return HttpResponse('邮箱格式错误')
else:
yanzhengma1=a.get('yanzhengma1')
yanzhengma2=a.get('yanzhengma2')
sname=a.get('sname')
snum=a.get('snum')
sclass=a.get('sclass')
pwd=a.get('pwd')
#连接数据库
db=pymysql.connect(
host='localhost',
port=3306,
user='root',
password='123456',
database='correct',
charset='utf8'
)
cursor=db.cursor()
sql1='select * from user'
cursor.execute(sql1)
allusers=cursor.fetchall()
i=0
while i<len(allusers):
if sid in allusers[i]:
isregistered=1
i+=1
if isregistered==0:
if yanzhengma1==yanzhengma2:
sql2='insert into user(sid,sname,snum,sclass,pwd) values (%s,%s,%s,%s,%s)'
cursor.execute(sql2,(sid,sname,snum,sclass,pwd))
db.commit()
cursor.close()
return HttpResponse('注册成功')
else:
return HttpResponse('验证码错误')
else:
cursor.close()
db.close()
return HttpResponse("该邮箱已注册")
参考:
https://blog.csdn.net/weixin_41238134/article/details/90318180
https://blog.csdn.net/LeoPhilo/article/details/89074232