使用Django默认电子邮件后端向Celery发送电子邮件

时间:2018-05-09 06:10:00

标签: django celery django-celery

我正在尝试使用Django和Celery向我的注册用户发送确认电子邮件。我使用RabbitMQ作为经纪人。每当我执行代码时,芹菜日志显示它正在接收任务并成功执行,但我没有收到任何电子邮件。

tasks.py

from celery.task import Task
from django.core.mail import send_mail
from django.template import loader
from django.utils.html import strip_tags
from config.celery import app
from config.settings import default


class SendConfirmationEmail(Task):

    def __init__(self, *args, **kwargs):
        self.user_name = kwargs.get('username')
        self.user_id = kwargs.get('id')
        self.user_hash = kwargs.get('hash')
        self.user_email = kwargs.get('email')

    def send_email(self):
        confirm_mail = loader.render_to_string('mail/confirmation.html',
                                           {'user': self.user_name, 'id': self.user_id,
                                            'hash': self.user_hash,
                                            'domain': default.SITE_URL})
        text_email = strip_tags(confirm_mail)
        send_mail(
            subject='Confirm Your E-mail',
            message=text_email,
            from_email='no-reply@mysite.com',
            recipient_list=[self.user_email],
            fail_silently=False,
            html_message=confirm_mail
        )

     def run(self, *args, **kwargs):
         self.send_email()

app.register_task(SendConfirmationEmail())

signals.py

from django.db.models.signals import post_save
from django.dispatch import receiver
from apps.siteuser.models import User
from apps.siteuser.tasks import SendConfirmationEmail


@receiver(post_save, sender=User)
def create_employee_details(sender, instance, created, **kwargs):
    if created:
        task = SendConfirmationEmail(username=instance.first_name, id=instance.id, hash=instance.hash,
                                 email=instance.email)
        task.delay()

电子邮件和电子邮件的设置芹菜:

CELERY_BROKER_URL = 'amqp://username:password@localhost:5672/vhost'

EMAIL_HOST = 'smtp.mailtrap.io'
EMAIL_HOST_USER = MY_USERNAME
EMAIL_HOST_PASSWORD = MY_PASSWORD
EMAIL_PORT = 2525

芹菜日志:

  

[2018-05-09 11:50:41,191:INFO / MainProcess]收到的任务:apps.user.tasks.SendConfirmationEmail [e63c0f5f-7b81-4065-85c1-9ef87acc792a]
  [2018-05-09 11:50:41,197:INFO / ForkPoolWorker-1]任务apps.user.tasks.SendConfirmationEmail [e63c0f5f-7b81-4065-85c1-9ef87acc792a]成功0.004487647999667388s:无

注意:我已经发送了没有Celery的邮件,它运行正常。但问题是在尝试使用Celery之后开始的。我正在使用Mailtrap进行开发。

1 个答案:

答案 0 :(得分:1)

这就是我通常称之为芹菜任务的方式

<强> Task.py

from celery import shared_task


@shared_task
def task1(*args,**kwargs):
    pass

<强> Caller.py

from task import task1


task1.delay(a,b,c...)

是否正确配置了芹菜发现?