django+ отправить электронное письмо в формате html с регистрацией django

StackOverflow https://stackoverflow.com/questions/1325983

Вопрос

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

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

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

Есть идеи?

Спасибо

Это было полезно?

Решение

Я бы рекомендовал отправить как текстовую, так и 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()

Другие советы

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

модели.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()

И в вашем бэкэнде регистрации просто используйте Хтмлрегистратионпрофиль вместо РегистрацияПрофиль.

Я знаю, что это устарело и регистрационный пакет больше не поддерживается.На случай, если кто-то еще этого захочет.Дополнительные шаги по отношению к ответу @bpierre:
- создать подкласс RegistrationView, т.е.view.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'),'

Этот парень расширил дефолтный Backend что позволяет нам добавить HTML-версию письма активации.

В частности, работа над альтернативной версией завершена. здесь

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top