我设置了一个系统 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 代码很重要。
当您使用 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-backed Celery 进行了测试,示例的输出取自 the official doc与预期相同。
关于python - 如何通过 Celery 发送 HTML 电子邮件?它不断发送文本/纯文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11489021/