如何通过 Celery 发送 HTML 电子邮件?它不断以文本/纯文本发送

Mic*_*ong 5 python django redis celery django-celery

我设置了一个系统 Django/Celery/Redis。我使用 EmailMultiAlternatives 发送 HTML 和文本电子邮件。

当我在请求过程中发送电子邮件时,电子邮件将以 HTML 格式发送。一切运行良好并且它包装了一个函数。这是代码:

def send_email(email, email_context={}, subject_template='', body_text_template='',
    body_html_template='', from_email=settings.DEFAULT_FROM_EMAIL):

    # render content
    subject = render_to_string([subject_template], context).replace('\n', ' ')
    body_text = render_to_string([body_text_template], context)
    body_html = render_to_string([body_html_template], context)

    # send email
    email = EmailMultiAlternatives(subject, body_text, from_email, [email])
    email.attach_alternative(body_html, 'text/html')
    email.send()
Run Code Online (Sandbox Code Playgroud)

然而,当我尝试将它作为 Celery 任务运行时,如下所示,它只是作为“文本/纯文本”发送。可能是什么问题呢?或者我可以做什么来了解更多信息?任何提示或解决方案都将不胜感激。

@task(name='tasks.email_features', ignore_result=True)
def email_features(user):
    email.send_email(user.email,
        email_context={'user': user},
        subject_template='emails/features_subject.txt',
        body_text_template='emails/features_body.txt',
        body_html_template='emails/features_body.html')
Run Code Online (Sandbox Code Playgroud)

okm*_*okm 4

Celery 不影响任务的执行结果。更改任务后是否重新启动了 celeryd?对于 celery 来说,重新加载 Python 代码很重要。

当您使用EmailMultiAlternatives和 时email.attach_alternative(body_html, 'text/html'),电子邮件是在 中发送的, 是Content-Type: multipart/alternative;text/html一种方式,渲染时根据邮件收据来选择邮件的内容类型。那么view程序和celery程序之间的收据是一样的吗?

您可以直接输出发送的邮件,通过python -m smtpd -n -c DebuggingServer localhost:25查看实际的消息。我已经在我的 Mac 上使用 Redis 支持的 Celery 进行了测试,从官方文档中获取的示例的输出与预期相同。