主要流程:
django通过发件服务器到收件服务器,最后到收件人
邮件配置设置需要打开SMTP/IMAP并获的授权码,完成授权功能实现发送给收件人
邮件配置请参考另一博客https://blog.csdn.net/qq_44238024/article/details/136277821
项目结构树
创建celery_taks目录配置celery环境
# main.pyimport os
from celery import Celery
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'web.settings')
app = Celery('celery_tasks')# 配置 broker
app.config_from_object('celery_tasks.config')# tasks ,所有tasks的路径
app.autodiscover_tasks(['celery_tasks.sms','celery_tasks.email'])
# config.py
broker_url = 'redis://127.0.0.1:6379/0'
创建email 任务tasks
# tasks.py
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):send_mail(subject=subject, message=message, from_email=from_email,recipient_list=recipient_list)
创建视图view.py调用celery
# view.py
def email_test(request):subject = '主题'message = '信息'from_email = 'xxx' # 发件人recipient_list = ['xxx@163.com'] # 收件人列表from celery_tasks.email.tasks import celery_send_email# 注意使用delay 函数才可以走异步调用celery_send_email.delay(subject=subject,message=message,from_email=from_email,recipient_list=recipient_list)return JsonResponse({'code':0,'data':'ok'})
配置setting的email 的全局信息
# =======email setting =========
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'xxx@163.com'
EMAIL_PORT = 25
EMAIL_HOST_USER = 'xxx@163.com' # 邮件发送人
EMAIL_HOST_PASSWORD = 'xxx' # 邮件授权码
EMAIL_FROM = "xxx" # 收件人看到的发件人
启动celery 命令
celery -A celery_tasks.main worker -l INFO
注意:只用才发这个命令时才走异步调用,而当没有下发命令,程序会等待其启动时异步调用