Python – Django Html email adds extra characters to the email body

djangoemailpython

I'm using Django to send an e-mail which has a text part, and an HTML part. Here's the code:

    subject = request.session.get('email_subject', None)
    from_email = request.session.get('user_email', None)
    to = request.session.get('user_email', None)
    bcc = [email.strip() for email in request.session.get('email_recipients', None).split(settings.EMAIL_DELIMITER)]

    text_content = render_to_response(email_text_template, {
        'body': request.session.get('email_body', None),
        'link': "http://%(site_url)s/ecard/?%(encoded_greeting)s" % {
            'site_url': settings.SITE_URL,
            'encoded_greeting': urlencode({'g': quote_plus(request.session.get('card_greeting'))}),
        },
    }, context_instance=RequestContext(request))

    html_content = render_to_response(email_html_template, {
        'body': request.session.get('email_body', None),
        'link': "http://%(site_url)s/ecard/?%(encoded_greeting)s" % {
            'site_url': settings.SITE_URL,
            'encoded_greeting': urlencode({'g': request.session.get('card_greeting')}),
        },
        'site_url': settings.SITE_URL,
    }, context_instance=RequestContext(request))

    email = EmailMultiAlternatives(subject, text_content, from_email, [to], bcc)
    email.attach_alternative(html_content, "text/html")
    sent = email.send()

When the user receives the email, it has this text in it: "Content-Type: text/html; charset=utf-8". Is there a good way to get rid of this?

Best Answer

You are generating html_content and text_content with render_to_response, which returns an HttpResponse object.

However you want html_content and text_content to be strings, so use render_to_string instead.

You can import render_to_string with the following line:

from django.template.loader import render_to_string