How to send HTML email via Celery? It keeps sending text / simple

I am setting up a Django / Celery / Redis system. And I used EmailMultiAlternatives to send my HTML email and text.

When I send an email as part of the request process, the email is sent in HTML format. Everything works well, and it wraps around the function. Here is the code:

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

However, when I tried to run it as a Celery task, as shown below, it just sent as "text / plain". What could be the problem? Or what can I do to find out more? Any hints or solutions are welcome.

 @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') 
+4
source share
1 answer

Celery does not affect the performance of tasks. Did you restart the celery after making changes to the assignment? For celery, it is important to reload the Python code.

When you used EmailMultiAlternatives and email.attach_alternative(body_html, 'text/html') , the message was sent to Content-Type: multipart/alternative; , and text/html is alternative, it depends on the mail receipts to select the type of mail content during rendering, Does the same apply to the viewing procedure and the celery procedure?

You can directly send sending mail via python -m smtpd -n -c DebuggingServer localhost:25 to find out the actual messages. I tested on my mac w / redis-backed Celery, the results of the examples taken from the white paper are the same as expected.

+4
source

All Articles