Django添加和验证邮箱

python编程快速上手(持续更新中…)

python实战项目(Django技术点)

1.添加邮箱

Django添加和验证邮箱_第1张图片

class EmailView(LoginRequiredJSONMixin, View):

    def put(self, request):
        # 1. 接收请求
        # put post --- body
        data = json.loads(request.body.decode())
        # 2. 获取数据
        email = data.get('email')
        # 验证数据
        # 正则 
        # 3. 保存邮箱地址
        user = request.user
        # user / request.user 就是 登录用户的 实例对象
        # user --> User
        user.email = email
        user.save()
return JsonResponse({
     'code': 0, 'errmsg': 'ok'})

2.邮箱授权

3.代码实现

email.tasks

# 2. 需要celery 自动检测指定包的任务
from django.core.mail import send_mail
from celery_tasks.main import app

@app.task
def celery_send_email(subject,message,from_email,recipient_list,html_message):

    send_mail(subject=subject,
              message=message,
              from_email=from_email,
              recipient_list=recipient_list,
              html_message=html_message)

users.view

# 4. 发送一封激活邮件
# 一会单独讲发送邮件
from django.core.mail import send_mail
# subject, message, from_email, recipient_list,
# subject,      主题
subject = '多多商城激活邮件'
# message,      邮件内容
message = ""
# from_email,   发件人
from_email = '多多商城'
# recipient_list, 收件人列表
recipient_list = ['[email protected]','[email protected]']

# 邮件的内容如果是 html 这个时候使用 html_message
# 4.1 对a标签的连接数据进行加密处理
# user_id=1
from apps.users.utils import generic_email_verify_token
token = generic_email_verify_token(request.user.id)

verify_url = "http://www.meiduo.site:8080/success_verify_email.html?token=%s" % token
# 4.2 组织我们的激活邮件
html_message = '

尊敬的用户您好!

'
\ '

感谢您使用多多商城。

'
\ '

您的邮箱为:%s 。请点击此链接激活您的邮箱:

'
\ '

%s

'
% (email, verify_url, verify_url) from celery_tasks.email.tasks import celery_send_email celery_send_email.delay( subject=subject, message=message, from_email=from_email, recipient_list=recipient_list, html_message=html_message )

4.启动celery(解耦)
celery -A celery_tasks.main worker -l info

5.激活邮件

Django添加和验证邮箱_第2张图片

class EmailVerifyView(View):

    def put(self, request):
        # 1. 接收请求
        params = request.GET
        # 2. 获取参数
        token = params.get('token')
        # 3. 验证参数
        if token is None:
            return JsonResponse({
     'code': 400, 'errmsg': '参数缺失'})
        # 4. 获取user_id
        from apps.users.utils import check_verify_token
        user_id = check_verify_token(token)
        if user_id is None:
            return JsonResponse({
     'code': 400, 'errmsg': '参数错误'})
        # 5. 根据用户id查询数据
        user = User.objects.get(id=user_id)
        # 6. 修改数据
        user.email_active = True
        user.save()
        # 7. 返回响应JSON
        return JsonResponse({
     'code': 0, 'errmsg': 'ok'})

你可能感兴趣的:(python,django,python,后端)