Django Html电子邮件为电子邮件正文添加了额外的字符

时间:2009-11-26 01:00:16

标签: python django email

我正在使用Django发送一封包含文本部分和HTML部分的电子邮件。这是代码:

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

当用户收到电子邮件时,其中包含以下文本:“Content-Type:text / html; charset = utf-8”。有没有一个好方法摆脱这个?

2 个答案:

答案 0 :(得分:5)

您正在使用html_content生成text_contentrender_to_response,这会返回HttpResponse个对象。

但是,您希望html_contenttext_content成为字符串,因此请改用render_to_string

您可以使用以下行导入render_to_string

from django.template.loader import render_to_string

答案 1 :(得分:2)

在你了解Alasdair的建议之前,启动shell并查看render_to_stringrender_to_response的输出。 shell可能会帮助你在将来找出这样的问题。

您提到的“Content-Type:text / html; charset = utf-8”行是HttpResponse生成的响应的标头。它是一个简单的HttpResponse对象标题中唯一的项目,就像你的例子中那样。

$ ./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
>>>