使用celery发送异步邮件

安装celery:pip install celery==4.2.1
windows系统安装:pip install eventlet
安装redis:pip install redis==2.10.6
启动:celery worker -A celery_tasks.tasks -l INFO -P eventlet

#celery_tasks/tasks.py
#使用celery
from celery import Celery
from django.core.mail import send_mail  #django自带发送邮件功能
from django.conf import settings    #使用settings.py里面的参数

import os
#django环境初始化,wsgi.py里的代码复制过来
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tiantianshengxian.settings")

#创建一个Celery类的实例对象
app = Celery("celsey_tasks.tasks", broker='redis://127.0.0.1:6379/8', backend='redis://127.0.0.1:6379/9')

#定义任务函数
@app.task
def send_register_active_emaiil(email,username,token):
    # 发邮件
    subject = "天天生鲜欢迎您注册"
    message = ""
    html_message = "

%s,欢迎您成功成为天天生鲜注册会员

请点击下面链接激活您的账户
http://127.0.0.1:8000/user/active/%s" % ( username, token, token) sender = settings.EMAIL_FROM # 发送者信息是获取settings文件中的配置 # 收件人列表,说明是可以给多个人进行发送的,email是获取前端的email receiver = [email] send_mail(subject, message, sender, receiver, html_message=html_message)
apps/user/views.py
#异步发邮件
        send_register_active_emaiil.delay(email,username,token)
#settings.py中设置邮箱参数
# QQ邮箱
# 发送邮件配置
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
# smtp服务器地址
EMAIL_HOST = "smtp.qq.com"
# smtp服务器端口号
EMAIL_PORT = 25
# 发送邮件的邮箱
EMAIL_HOST_USER = "[email protected]"
# 邮箱的授权密码
EMAIL_HOST_PASSWORD = "tqedjyivbapkghaj"
# 收件人看到的发件人
EMAIL_FROM = "天天生鲜<[email protected]>"

你可能感兴趣的:(使用celery发送异步邮件)