views:

111

answers:

2

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?

+3  A: 

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
Alasdair
+1  A: 

Before you go with Alasdair's suggestion, fire up the shell and take a look at the output from render_to_string and render_to_response. The shell just might help you figure out a problem like this in the future.

The "Content-Type: text/html; charset=utf-8" line that you mentioned is the header for the response generated by HttpResponse. It is the only item in the header for a simple HttpResponse object like the one in your example.

$ ./manage.py shell
Python 2.6.3 (r263:75183, Oct 14 2009, 15:40:24) 
Type "help", "copyright", "credits" or "license" for more information.
>>> from django.shortcuts import render_to_response
>>> from django.template.loader import render_to_string
>>> template = 'your_template.html'
>>> print( "\n".join(render_to_string(template).split('\n')[:3]) )
template-line-1
template-line-2
template-line-3
>>> print( "\n".join(str(render_to_response(template)).split('\n')[:3]) )
Content-Type: text/html; charset=utf-8

template-line-1
>>>
istruble