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

标签 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()

但是,当我尝试将其作为 Celery 任务运行时,如下所示,它只是作为“text/plain”发送。可能是什么问题呢?或者我可以做些什么来了解更多信息?非常感谢任何提示或解决方案。

@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')

最佳答案

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

当您使用 EmailMultiAlternativesemail.attach_alternative(body_html, 'text/html') 时,电子邮件在 Content-Type: multipart 中发送/alternative;text/html 是替代的,它在渲染时根据邮件回执来选择邮件的内容类型。那么 View 程序和 celery 程序之间的收据是否相同?

您可以直接输出发送邮件,通过python -m smtpd -n -c DebuggingServer localhost:25 找出实际的消息。我已经在我的 mac 上使用 redis-backed Celery 进行了测试,示例的输出取自 the official doc与预期相同。

关于python - 如何通过 Celery 发送 HTML 电子邮件?它不断发送文本/纯文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11489021/

相关文章:

python - 将文档字符串添加到命名元组?

python - 仅使用 Spacy Phrasematcher 才能实现最长匹配

node.js - NodeBB (Redis) 找回用户名和密码

python - 仅从电子邮件中检索新消息

python - 为什么文件没有上传到 Django 模型中指定的上传路径,当从管理员上传时它正在上传到预期的目录

ajax put 返回 500 内部服务器错误

django - 如何创建 Django 数据库备份?

python - Django 与 Tornado

parse-platform - 为实时查询设置解析和 redis

heroku - 使用 Redis 解析 LiveQuery 独立服务器