zoukankan      html  css  js  c++  java
  • celery 异步发送邮件

    1.settings同级目录下创建 celery 文件

    from __future__ import absolute_import, unicode_literals
    import os
    from celery import Celery
    
    # 设置环境变量
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', '项目名.settings')
    
    # 注册Celery的APP
    app = Celery('项目名')
    # 绑定配置文件
    app.config_from_object('django.conf:settings', namespace='CELERY')
    
    # 自动发现各个app下的tasks.py文件
    app.autodiscover_tasks()

    2 配置settings文件

    # 发送方 邮箱账户
    my_mail = '4544****@qq.com'
    # 发送发 邮箱授权码
    my_pass = 'd*****'
    
    
    
    
    # celery  参数
    
    CELERY_BROKER_URL = 'redis://127.0.0.1:6379/'
    
    CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/'
    
    CELERY_RESULT_SERIALIZER = 'json'

    3 配置 settings同级目录下 init 文件

    from __future__ import absolute_import, unicode_literals
    from .celery import app as celery_app
    
    #导包
    import pymysql
    #初始化
    pymysql.install_as_MySQLdb()
    
    
    
    __all__ = ['celery_app']

    4 工具py里 创建发邮件的类

    from syl.settings import *
    from celery.task import task
    
    # 定义发送邮件的方法
    @task
    def send_mail(subject, content, mailaddr):
        
        sleep(5)
        res = True
        try:
            # 声明邮件对象
            msg = MIMEText(content, 'plain', 'utf-8')
    
            # 设置发送方对象
            msg['From'] = formataddr(['自定义标题', my_mail])
    
            # 设置收件方对象
            msg['To'] = formataddr(['尊敬的客户', mailaddr])
    
            # 设置标题
            msg['Subject'] = subject
    
            # 设置smtp服务器
            server = smtplib.SMTP_SSL("smtp.qq.com", 465)
    
            # 登录邮箱
            server.login(my_mail, my_pass)
    
            # 发送邮件
            server.sendmail(my_mail, [mailaddr], msg.as_string())
    
            # 关闭smtp链接
            server.quit()
        except Exception as e:
            print(e)
            res = False
            return res
        return res

    5 调用接口

    class Send_email(APIView):
    
        # 注册
        def post(self, request):
    # 接收邮件的 邮箱 email= request.POST.get('email')
    user = User.objects.filter(email=email)
    if user: return Response({'code': 222, 'message': '该用户名已被注册'}) try: # 邮件 subject = "账号激活" content = '自定义内容' mail.delay(subject, content,email)
    return Response({'code': 200, 'address': '验证链接已发送到您的邮箱,请前往激活账号'}) except Exception as e: print(e) return Response({'code': 400})

    6 先启动django项目 然后另开终端 cd到celery 目录下启动celery 服务

    celery worker -A 项目名 --loglevel=info --pool=solo

    classSyl_user(APIView):# 注册defpost(self, request):# 用户名重复校验 name = request.POST.get('username')# 接收邮件的 邮箱 recipient = request.POST.get('email') user = User.objects.filter(username=name)if user:return Response({'code':222,'message':'该用户名已被注册'}) data = request.POST.copy()# 弹出密码 password = data.pop('password')# 密码加密 password = make_password(password[0])# 密码放回 data['password']= password try: se = UserSer(data=data) se.is_valid() se.save() user = User.objects.get(username=name) uid = user.id plyload ={'iss':'实验二楼','iat':int(time.time()),'exp':int(time.time())+300,'uid': uid,} key = jwt.encode(plyload,'jiang', algorithm='HS256')print(key.decode('utf-8'))# 邮件 subject ="账号激活" content ="点击链接激活账号:http://localhost:8000?token="+ key.decode('utf-8')+'.com' mail.delay(subject, content,recipient)print(recipient)return Response({'code':200,'address':'验证链接已发送到您的邮箱,请前往激活账号'})except Exception as e:print(e)return Response({'code':400,'message': se.errors})

  • 相关阅读:
    ADB命令大全
    Backup your Android without root or custom recovery -- adb backup
    Content portal for Pocketables Tasker articles
    Is there a way to detect if call is in progress? Phone Event
    Tasker to proximity screen off
    Tasker to detect application running in background
    Tasker to create toggle widget for ES ftp service -- Send Intent
    Tasker to proximity screen on
    Tasker to answer incoming call by pressing power button
    Tasker to stop Poweramp control for the headset while there is an incoming SMS
  • 原文地址:https://www.cnblogs.com/weiwuhu/p/13418648.html
Copyright © 2011-2022 走看看