Django + отправить электронное письмо в html с django-registration
im, используя django-registration, все в порядке, письмо с подтверждением отправлялось в текстовом виде, но знаю, что im исправлено и отправляется в html, но у меня проблема с мусором... html-код показывает:
<a href="#" onclick="location.href='http://www.example.com/accounts/activate/46656b86eefc490baf4170134429d83068642139/'; return false;">http://www. example.com/accounts/activate/46656b86eefc490baf4170134429d83068642139/</a>
и мне не нужно показывать html-код, например...
Любая идея?
Спасибо
Ответы
Ответ 1
Я бы рекомендовал отправить текстовую версию и версию 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', '[email protected]', '[email protected]'
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
Чтобы избежать исправления 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.
Ответ 3
Я знаю, что это устарело, и пакет регистрации больше не поддерживается. На всякий случай кто-то все еще хочет этого.
Дополнительные шаги по ответу @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'),'
Ответ 4
Этот парень расширил defaultBackend, чтобы добавить HTML-версию электронного письма активации.
В частности, задание альтернативной версии выполняется здесь
Мне удалось успешно использовать бэкэнд-часть