如何在Django中使用Celery进行邮件发送

2023-04-11 00:00:00 django 如何在 邮件发送

步骤如下:

  1. 安装Celery和redis
pip install celery
pip install redis
  1. 在settings.py中配置Celery和redis
# settings.py

CELERY_BROKER_URL = 'redis://localhost:6379/0'
CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'

CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'

INSTALLED_APPS = [
    # ...
    'django_celery_results',
]

# celery settings
CELERY_TIMEZONE = 'UTC'
CELERY_IGNORE_RESULT = False
CELERY_TASK_TRACK_STARTED = True
CELERYD_HIJACK_ROOT_LOGGER = False
CELERYD_PREFETCH_MULTIPLIER = 1
CELERY_ACKS_LATE = True
CELERYD_CONCURRENCY = 4
CELERYD_TASK_TIME_LIMIT = 300
CELERYD_TASK_SOFT_TIME_LIMIT = 60

# django-celery-results settings
CELERY_RESULT_BACKEND = 'django-db'
  1. 定义Celery任务
# tasks.py

from celery import shared_task
from django.core.mail import send_mail

@shared_task
def send_email_task():
    email_subject = 'Welcome to pidancode.com'
    email_body = 'Thank you for choosing pidancode.com for all of your coding needs.'
    sender_email = 'example@pidancode.com'
    recipient_email = 'recipient@example.com'

    send_mail(
        email_subject,
        email_body,
        sender_email,
        [recipient_email],
        fail_silently=False,
    )
  1. 在视图中调用Celery任务
# views.py

from django.shortcuts import render
from .tasks import send_email_task

def send_email_view(request):
    if request.method == 'POST':
        send_email_task.delay()
        return render(request, 'success.html')

    return render(request, 'send_email.html')
  1. 运行Celery
celery -A your_project_name worker -l info
  1. 在发送邮件之前需要保证redis启动
redis-server

在send_email.html中添加一个表单:

<!-- send_email.html -->

<form method="POST">
  {% csrf_token %}
  <button type="submit" class="btn-primary">Send Email</button>
</form>

这样就完成了使用Celery在Django中进行异步邮件发送的过程。当用户在Web界面中填写邮件相关信息并提交表单时,Django将调用Celery任务,将发送邮件放入消息队列,而后续的异步任务处理和发送将由Celery和redis来管理和处理。

相关文章