使用Django生成验证码 并发送qq邮箱

一、登录QQ邮箱–>设置–>账户–>POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务

使用Django生成验证码 并发送qq邮箱
使用Django生成验证码 并发送qq邮箱

 
# 设置邮件域名 发送邮件服务器:smtp.qq.com
EMAIL_HOST = 'smtp.qq.com'
# 设置端口号,为数字  使用SSL,端口号465或587
EMAIL_PORT = 25
# 设置发件人邮箱
EMAIL_HOST_USER = 'xxxxxxx'
# 设置发件人授权码
EMAIL_HOST_PASSWORD = 'xxxxxxxx'
# 设置是否启用安全连接
EMAIL_USE_TLS = True
 # redis连接
REDIS_CON = redis.StrictRedis(host='localhost', port=6379)
 # 随机验证码
def vercode(user):
    res1 = ''
    for i in range(4):
        num = random.randint(0, 9)
        res1 += str(num)
        REDIS_CON.set(f'{user}', res1)
        REDIS_CON.expire(f'{user}', 10)
    return res1

class Send_Email(View):
    def get(self, request):
        re_send = request.GET.get('email')
        sbj = '测试邮箱发送验证码'
        msg = f'您的验证码为:{vercode(re_send)}'
        from_send = EMAIL_HOST_USER
        # subject 标题 message 内容 from_email 发送人 recipient_list 接收人(多个)
        res = send_mail(subject=sbj, message=msg, from_email=from_send, recipient_list=[re_send])
        if res == 1:
            return render(request, 'send_email.html')
        else:
            return render(request, 'send_email.html')

class register(View):
    def get(self, request):
        code = request.GET.get('code')
        email = request.GET.get('email')
        if email:
            scode = REDIS_CON.get(email)
            if scode:
                if code == scode.decode('utf-8'):
                    print('验证成功')
                else:
                    print('验证码不正确')
            else:
                print('验证码已失效')
        else:
            print('邮箱不正确')
        return HttpResponse('ok')

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>发送邮箱</title>
    <script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
邮箱:<input type="text" name="email" id="email_id">
<input type='submit' value="发送邮箱" onclick="send()">
</body>
<script>
    function send() {
        $.ajax({
            url:'http://127.0.0.1:8000/app01/send_email/',
            method:'get',
            data:{
                'email':document.getElementById('email_id').value
            }
        })
    }
</script>
</html>

上一篇:日志文件分析


下一篇:Python 发送企业微信单发和群发机器人