django中的电子邮件模板

时间:2014-12-19 09:57:01

标签: python django email

我在html中创建了一个电子邮件模板,我使用下面的视图发送电子邮件,工作正常。但是当我收到以RAW html格式显示的电子邮件时。我可以知道错误是什么。

def confirmed_email_notification(sender, **kwargs):
    """
    Sends an email notification to the shop owner when a new order is
    completed.
    """
    print "EMAIL NOTIFICATION "
    subject_template_name = 'shop_simplenotifications/confirmed_subject.txt'
    body_template_name = 'shop_simplenotifications/confirmed_body.html'
    request = kwargs.get('request')
    order = kwargs.get('order')
    subject = loader.render_to_string(
        subject_template_name,
        RequestContext(request, {'order': order})
    )
    subject = subject.join(subject.splitlines())
    body = loader.render_to_string(
        body_template_name,
        RequestContext(request, {'order': order})
    )
    from_email = getattr(settings, 'SN_FROM_EMAIL',
                         settings.DEFAULT_FROM_EMAIL)
    owners = getattr(settings, 'SN_OWNERS', settings.ADMINS)
    send_mail(subject, body, from_email,
              [owner[1] for owner in owners], fail_silently=False)
    print body
    print [owner[1] for owner in owners]
confirmed.connect(confirmed_email_notification)

1 个答案:

答案 0 :(得分:0)

如果您正在使用django 1.7,则可以将消息的html版本作为send_mail()参数传递给html_message,cf https://docs.djangoproject.com/en/1.7/topics/email/#send-mail

否则,您可以使用此处记录的EmailMultiAlternatives类: https://docs.djangoproject.com/en/1.6/topics/email/#sending-alternative-content-types

或使用EmailMessage类并将content_subtype属性设置为" html"。

只是旁注:我真的怀疑subject.join(subject.splitlines())做你期望的事情:

>>> subject = "hello Huston\nWe have a\nproblem"
>>> print subject.join(subject.splitlines())
hello Hustonhello Huston
We have a
problemWe have ahello Huston
We have a
problemproblem
>>>