django celery 发邮件

安装依赖 pip

celery==3.1.26.post2
celery-with-redis==3.0
django-celery==3.2.2

settings.py设置

import djcelery
from celery import platforms

INSTALLED_APPS = [
    'djcelery',
]

platforms.C_FORCE_ROOT = True  #加上这一行
djcelery.setup_loader()
BROKER_URL = 'redis://%s:%s/%s' % (records['redis_host'], records['redis_port'], records['redis_db'])
CELERY_IMPORTS = ('signup.signup')


EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = records['email_host']
EMAIL_PORT = records['email_port']
# 如果是在阿里云上运行的服务器需要将端口改为465,并设置EMAIL_USE_SSL = True
# EMAIL_USE_SSL = True
EMAIL_USE_TLS = True
# 发送邮件的邮箱
EMAIL_HOST_USER = records['email_host_user']
# 在邮箱中设置的客户端授权密码
EMAIL_HOST_PASSWORD = records['email_host_password']
# 收件人看到的发件人
EMAIL_FROM = records['email_from']

conf.json设置

{
  "redis_host": "127.0.0.1",
  "redis_port": "6379",
  "redis_db": "7",
  "email_host": "smtp.office365.com",
  "email_port": 587,
  "email_host_user": "[email protected]",
  "email_host_password": "1234567",
  "email_from": "Example",
  "email_subject": "Example Email",
  "email_message": ""
}

sign文件夹下sign.py文件

from django.conf import settings
from django.core.mail import send_mail

@task
def send_active_email(emails):

    try:
        subject = jc.email_subject # 标题
        message = jc.email_message
        sender = settings.EMAIL_FROM # 发件人
        receiver = emails # 收件人列表
        with open("signup/message.html", "r") as f:
            html_message = f.read()
        send_mail(subject, message, sender, receiver, html_message=html_message)
    except Exception as e:
        logger.error(e)
        logger.error('Error: send message failed')

def register(request):

    email = request.POST.get('email')
    try:
        send_active_email.delay([email])
        return JsonResponse({'code': 'success', 'message': 'Register successfully'})
    except Exception as e:
        logger.error(e)
        return JsonResponse({'code': 'failure', 'message': 'Fail to register'})

打开两个终端
一个运行python3 manage.py server
一个运行python3 manage.py celery worker --loglevel=info

你可能感兴趣的:(django celery 发邮件)