Django + отправить письмо в формате HTML с Django-регистрации - PullRequest
11 голосов
/ 25 августа 2009

я использую django-регистрацию, все в порядке, электронное письмо с подтверждением отправляло в виде обычного текста, но я знаю, что я исправил и отправляю в html, но у меня проблема с мусором ... HTML-код показывает:

<a href="http://www.example.com/accounts/activate/46656b86eefc490baf4170134429d83068642139/">http://www. example.com/accounts/activate/46656b86eefc490baf4170134429d83068642139/</a>

и мне не нужно показывать HTML-код, как ...

Есть идеи?

Спасибо

Ответы [ 4 ]

27 голосов
/ 26 февраля 2011

Чтобы избежать внесения исправлений в django-регистрацию, вы должны расширить модель RegistrationProfile с помощью proxy = True :

models.py

class HtmlRegistrationProfile(RegistrationProfile):
    class Meta:
        proxy = True
    def send_activation_email(self, site):
        """Send the activation mail"""
        from django.core.mail import EmailMultiAlternatives
        from django.template.loader import render_to_string

        ctx_dict = {'activation_key': self.activation_key,
                    'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
                    'site': site}
        subject = render_to_string('registration/activation_email_subject.txt',
                                   ctx_dict)
        # Email subject *must not* contain newlines
        subject = ''.join(subject.splitlines())

        message_text = render_to_string('registration/activation_email.txt', ctx_dict)
        message_html = render_to_string('registration/activation_email.html', ctx_dict)

        msg = EmailMultiAlternatives(subject, message_text, settings.DEFAULT_FROM_EMAIL, [self.user.email])
        msg.attach_alternative(message_html, "text/html")
        msg.send()

А в вашей регистрационной системе просто используйте HtmlRegistrationProfile вместо RegistrationProfile .

14 голосов
/ 12 сентября 2009

Я бы рекомендовал отправлять как текстовую, так и HTML-версию. Поищите в файле models.py регистрации django:

send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [self.user.email])

и вместо этого сделайте что-нибудь подобное из документов http://docs.djangoproject.com/en/dev/topics/email/#sending-alternative-content-types

from django.core.mail import EmailMultiAlternatives

subject, from_email, to = 'hello', 'from@example.com', 'to@example.com'
text_content = 'This is an important message.'
html_content = '<p>This is an <strong>important</strong> message.</p>'
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
2 голосов
/ 08 декабря 2014

Я знаю, что это старый и пакет регистрации больше не поддерживается. На всякий случай, если кто-то все еще хочет этого. Дополнительные ответы по отношению к ответу @bpierre:
- подклассы RegistrationView, т.е. views.py

вашего приложения
class MyRegistrationView(RegistrationView):
...
def register(self, request, **cleaned_data):
    ...
    new_user = HtmlRegistrationProfile.objects.create_inactive_user(username, email, password, site)

- в вашем urls.py измените представление на подклассическое представление, т.е. - Элемент списка

url(r'accounts/register/$', MyRegistrationView.as_view(form_class=RegistrationForm), name='registration_register'),'
0 голосов
/ 22 ноября 2012

Этот парень расширил defaultBackend , что позволило нам добавить HTML-версию письма активации.

В частности, задание альтернативной версии выполнено здесь

Мне удалось успешно использовать серверную часть

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...